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;

}

Recommended Answers

All 3 Replies

Please elaborate on what these "errors" are.

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.