Search code examples
cintegerfopenread-write

Error with reading and writing long data type incrementally in C


I have the following code:

#include <stdio.h>
#include <stdlib.h>

int main() {
  long num = 0;
  FILE *fptr;

     if ((fptr = fopen("test_num.txt","r+")) == NULL){
         printf("Error! opening file");
         return -1;
     }

     fscanf(fptr,"%ld", &num);

     // Increment counter by 1
     num += 1;

     printf("%ld\n", num);
     fprintf(fptr, "%ld", num);
     fclose(fptr);

     return -1;

}

With the aforementioned code I am trying to read the content of the file, which always has a long value stored and nothing else, increment the value by 1 and then overwrite the lond value of the file with the new incremented value. However, I am trying to do this without closing and file in between reading/writing. Fo example, the workflow/algorithm should be as follows:

Step 1: Open the file
Step 2: Read the long value from the file
Step 3: Increment the long value by 1
Step 4: Overwrite the long value of the file by new incremented value
Step 5: Close the file

However, if I use the aforementioned code then the output value appends the incremented value at the end of the file instead of overwriting. I have tried opening the file with "w+" and "w" but of course these only work for writing but not reading the file as mentioned above. Can anyone know what I can do to achieve the goal?


Solution

  • The answer happens to be: I needed to rewind the file ponter back to the index 0 of the file in order to overwrite the content of the file with the incremented value. The correct code is as follows:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
      long num = 0;
      FILE *fptr;
    
         if ((fptr = fopen("test_num.txt","r+")) == NULL){
             printf("Error! opening file");
             return -1;
         }
    
         fscanf(fptr,"%ld", &num);
    
         // Increment counter by 1
         num += 1;
    
         printf("%ld\n", num);
         rewind(fptr); // Rewind to index 0 of the fptr
         fprintf(fptr, "%ld", num);
         fclose(fptr);
    
         return -1;
    
    }