Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 766
Aneesh Dogra Avatar asked Jan 14 '16 13:01

Aneesh Dogra


People also ask

What is the purpose of fscanf and fprintf in C?

fprintf () function writes formatted data to a file. fscanf () function reads formatted data from a file. fputchar () function writes a character onto the output screen from keyboard input.

Is used to handle mixed type of data C Fprint fscanf get PUTC gets put?

C language provides two functions fprintf() and fscanf() for handling a set of mixed data values. The function fprintf() is used to write a mix of different data items into a specified file.


1 Answers

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);
like image 186
Danny_ds Avatar answered Nov 06 '22 23:11

Danny_ds