6
#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?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Aneesh Dogra
  • 740
  • 5
  • 30

1 Answers1

8

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);
Danny_ds
  • 11,201
  • 1
  • 24
  • 46
  • `rewind(fp)` is probably better, as it also has the effect (for files opened for updating) of preparing for a switch between reading and writing. – Peter Jan 14 '16 at 13:43