简体   繁体   中英

Using fscanf and fprintf together in C

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

#define FILE_NAME "ff.txt"

int main() {        
    char x[10],y[10];
    FILE *fp;
    fp = fopen(FILE_NAME, "r+");
    if (fp == NULL) {
        printf("couldn't find %s\n ",FILE_NAME);
        exit(EXIT_FAILURE);         

    }
    fprintf(fp,"Hello2 World\n");
    fflush(fp);   
    fscanf(fp,"%s %s",x,y);
    printf("%s %s",x,y);
    fclose(fp);
    return 0;
}

Here's a boiled down version of what I am trying to do. This code doesn't print anything in the console. If I remove the fprintf call, it prints the first 2 strings in the file, for me its Hello2 World . Why is this happening? Even after I fflush the fp ?

After fprintf() , the file pointer points to the end of the file. You can use fseek() to set the filepointer at the start of the file:

fprintf(fp,"Hello2 World\n");
fflush(fp);   
fseek(fp, 0, SEEK_SET);
fscanf(fp,"%s %s",x,y);

Or even better as suggested by @Peter, use rewind() :

rewind(fp);

rewind :

The end-of-file and error internal indicators associated to the stream are cleared after a successful call to this function, and all effects from previous calls to ungetc on this stream are dropped.

On streams open for update (read+write), a call to rewind allows to switch between reading and writing.

It is always best to check the return code of fscanf() too.

To avoid buffer overflow, you can use:

fscanf(fp,"%9s %9s",x,y);

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