简体   繁体   中英

trying read and write on the same code in c program

Help I'm trying to write the data in the file. then, trying to read it back, but its not working.

#include <stdio.h>
    
int main(void) {
    FILE *fptr = fopen("try.txt", "r+");
    char line[1000];
    
    fprintf(fptr, "i have new number = 1425");
        
    while (fgets(line, 1000, fptr)) {
        printf("%s",line);
    }
    
    return 0;
}

You must use a positioning function such as rewind() or fseek() between read and write operations.

Beware that the update mode for streams is very confusing and error prone, you should avoid using it and structure your programs accordingly.

Incidentally, your program will fail to open try.txt if it does not already exist, but you do not check for fopen failure so you will get undefined behavior in this case.

Here is a modified version:

#include <stdio.h>
    
int main(void) {
    char line[1000];
    FILE *fptr = fopen("try.txt", "w+");
    
    if (fptr != NULL) {
        fprintf(fptr, "I have new number = 1425\n");
        
        rewind(fptr);
        while (fgets(line, sizeof line, fptr)) {
            printf("%s", line);
        }
        fclose(fptr);
    }
    return 0;
}

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