0

Iam beginer in this field. While trying a code to implement fprintf & fscanf, iam getting errors.
Please help to explain the cause of error.

Code Snippet

#include <stdio.h>

int main ()
{
  FILE *fp;

  int num;
  char sstr[100];
  fp = fopen("myText.txt", "w");
  fprintf(fp,"%d %s",9898,"visakh");

  /*sscanf(fp, "%f %s",&ffloat,sstr);
  printf("Float = %f\n",ffloat);
  printf("String : ");
  puts(sstr);*/
  //rewind(fp);
  fscanf(fp,"%d",&num);
  fscanf(fp, "%s",sstr);
  printf("NUM = %d\n",num);
  printf("String : %s",sstr);
  //puts(sstr);
  fclose(fp);
  return 0;

}
4
Contributors
3
Replies
17
Views
3 Years
Discussion Span
Last Post by mathematician
0

The file is open for writing only. fscanf() is a read function. Solve the problem like this:

line 9: open the file with "rw" flag

line 15: uncomment that line.

add a new line just before line 15: fflush(fp); which will force everything to be physically written to disk. Until then the data could be just cashed in memory.

0

If the file doesn't aleady exist, you need to open it with "w+" to reate a file for eading and writing. If it does already exist, you need to open it with "r+" for reading and writing.

Not terribly logical, but there you are.

Warning: If you try to open an existing file with "w+", the file will be deleted, and a new one with the same name created.

Edited by mathematician

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.