Somdip Dey
Somdip Dey

Reputation: 3396

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?

Upvotes: 0

Views: 55

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409482

There are two common ways to rewrite parts of a text-file:

  1. Read the while file into memory, make the change, and write it back out from the beginning.

  2. Read parts of the file (for example line by line), making the change on the fly, and writing to a new temporary file. Then rename the temporary file as the actual file.

Upvotes: 0

Somdip Dey
Somdip Dey

Reputation: 3396

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;

}

Upvotes: 1

Related Questions