Muaz Yasin
Muaz Yasin

Reputation: 21

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;
}

Upvotes: 0

Views: 36

Answers (1)

chqrlie
chqrlie

Reputation: 144550

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;
}

Upvotes: 1

Related Questions