Good day! I ask you to tell me about the entry of data in the file, and most importantly - reading from the file. I know the fscanf function, but for some reason, its calling does not give me what I need. I want to clarify, fprintf - puts data into a file, and fscanf - copies from file to a variable? Here is my program:

  FILE *fp; fp=fopen("ro.txt", "w"); printf("vozrast? \n"); scanf ("%d", &K); fprintf(fp, "%d", K); fp=fopen("ro.txt", "r"); while (!feof(fp)) { fscanf(fp, "%d", &new_K); } printf("%d", new_K); 

As I understand it, the number should be recorded from the notepad in new_k , however, for some reason, a foreign value is recorded and displayed on the screen. Tell me, plz, what am I wrong?

    3 answers 3

    There is such a thing - a system carriage. So, first you write to the file, the caret goes to the end of the file. Then you read from the file, but the caret is already at the end of the file. In order not to close-open the file tens of thousands of times, use the fseek () function (google for parameters and details). First, write to the file, then call, for example, fseek (fp, 0, SEEK_SET); and then read, but from the beginning of the file.

    • 2
      Yes, but then let him open with the parameter "w +" - skegg
    • Happened. Thank you very much!!! - Kollibry
    • If it works, the answer is supposed to be accepted). - 3JIoi_Hy6
    • done) thanks - Kollibry

    The error lying on the surface is that you do not close the file (FILE * fp), opened for writing, again open it for reading using the same variable . Just add fclose (fp) before the second fopen ().

    The fact is that stdio implements output buffering. You called fprintf (), the data got into the buffer, but nobody copied it to the disk (or more precisely into the OS buffer). They will move there in the following cases.

    1) recorded a lot of data (more than the buffer size in stdio)

    2) called the fflush () function

    3) performed fclose ().

    After that they can be read.

      It is not very clear what variable fp is written to. To write something to a file, you must first open it for writing, get a stream, write it there and close it. Then open again for reading, etc.

      • FILE * fp; fp = fopen ("ro.txt", "w"); I apologize)) here are the first two lines. Of course, I opened the file, just to save space I did not add these lines - Kollibry pm
      • Well, first close it, then open it again to read. - skegg