简体   繁体   中英

How can I use fopen "w+" in c to write and read the same file?

I was looking how to write and read a file using C. After discovering that usign fopen("foo", "r+") or fopen("foo", "w+") it should be possible, I decided to create a dummy program just to try it. This is the program:

#include <stdio.h>
int main(){
    char reader[81];
    FILE *USE = fopen("dummy.txt", "w+");
    fprintf(USE,"whatever \r\nhello");
    while(fgets(reader, 80, USE)) {
        printf("%s", reader);
    }
    fclose(USE);
    return 0;
}

The idea was to create a new file called dummy.txt. Everytime this program is executed writes 2 lines in dummy.txt and then display those lines in the command line or terminal. As you can see it is not the most useful program ever but knowing how to do this can be very helpful in the future.

Any help is wellcome

For reading the file again you should use rewind function:

 fprintf(USE,"whatever \r\nhello");

 rewind(USE); // put the file pointer to the begin of file;

 while(fgets(reader, 80, USE));

another way is using fseek :

int fseek(FILE *stream, long int offset, int whence)

where:

  • stream − This is the pointer to a FILE object that identifies the stream.

  • offset − This is the number of bytes to offset from whence.

  • whence − This is the position from where offset is added. It is
    specified by one of the following constants:

     1 - SEEK_SET Beginning of file 2 - SEEK_CUR Current position of the file pointer 3 - SEEK_END End of file

Also you can use:

long int ftell ( FILE * stream ); 

for the current position in stream.

Here , more about fseek vs rewind

You forgot to rewind the file:

fprintf(USE,"whatever \r\nhello");

rewind(USE);   //<<< add this

while(fgets(reader, 80, USE)) {

Once you have written into the file, the file pointer is at the end of the file. So in order to read what you have written, you must set the file pointer to the beginning of the file using rewind .

If you want to put the file pointer elsewhere than at the beginning, use fseek . And ftell will tell you where the file pointer currently is.

Side note not related to your problem

Don't use all uppercase variable names such as USE , all uppercase names are usually used for macros only.

My solution, don't use w+ but r+.

Top of the file

#include <stdio.h>
#include <stdlib.h>

Global

FILE * g_file;

Open File

int openFile() {
    g_file = fopen("my_file.txt", "r+");
    if( g_file == NULL )
    {
        // No file ?
        g_file = fopen("my_file.txt", "w+");
    }
    return 0;
}

Read and Write

#define MAX 64
#define true  1
#define false 0

int writeReadFile() {
    char line[MAX] = "";
    int size = 0;

    while( fgets(line, MAX, g_file) )
    {
        // Check something
        // result = sscanf(line, etc...)
        // if ( result == argument number ok) ...
        // strcmp( ? , ? ) == 0
        // strlen compare size of the previous line and new line   
        if ( true ) {
            size = ftell(g_file);
        }

        // Replace something
        if( true ) {
            fseek(g_file, size, SEEK_SET);            
            // fputc if size differ
            // fprintf if size ok
        }
        size = ftell(g_file);
    }
    fprintf(g_file, "%s\n", "info");
}

The main

int main(void)
{
    printf("Hello World !\n");

    openFile();
    writeReadFile();

    return 0;
}

Please do not delete my post. Once I wrote this. I receive the link from the page, save it and I can reuse it for other codes. So, do not delete. Thank you.

He compiles on my side, also hoping for you. Please , remove and do not put bad notes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM