Search code examples
ciostreamfseek

How to read a file that was fseeked?


I have no idea why this does not work:

#include <stdio.h>

int main(){
    FILE* fp = fopen("txt2","wr");
    if(!fp) return 1;

    fprintf(fp,"20");
    fseek(fp,0,SEEK_SET);   
    fprintf(fp,"19");
    rewind(fp);
    
    char c;
    while((c=fgetc(fp))!=EOF)
        printf("%c",c);
}

Here should be write 20, then rewrite to 19, set the position to start of file, and the read the char till EOF (so should print 19). But prints nothing. Why is that?

I have tried to make better check for return poitner to fp (because of wr):

EDIT:

#include <stdio.h>
int main(){
    FILE *fp = fopen("txt","wr");
    if(!fp){
        printf("nada\n");
        return 1;
    }
}

But it compiles without problem. Why is that? The wr should be UB (and thus cause segfault or another err) or?


Solution

  • The mode "wr" is not valid string for POSIX fopen() or Microsoft fopen(). You probably want to use "w+". Using "r+" would be an alternative, but then the file must exist before you open it.

    The implementation of fopen() that you're using probably treats "wr" as equivalent to "w" (unless it reports an error and your program exits — it is a good idea to report why you are exiting). You can't read from a write-only file stream.

    Strictly, you should also use int and not char for the variable c because fgetc() returns an int.