Saptarshi Biswas
Saptarshi Biswas

Reputation: 23

How to edit a number which is at a specific location in a given file in C?

I have saved a list of number as

1
2
3
4
5
6
7
8
9
10

in the file INPUT.txt. and I want to edit a specific location (which is the 5th element here) and want to replace it by number 35. How can I do this? (I do not want to create another new file, neither I want to overwrite the whole thing, just editing that file only!!).

#include <stdio.h> 

void main() { 
    FILE *fp; 
    char ch; 
    int a, i, b = 35;
    fp = fopen("INPUT.txt", "r+");

    for (i = 0; i < 10; i++) {
        fscanf(fp, "%d", &a);
        printf("\t%d\n", a);
        if (i == 5) {
            fprintf(fp, "b");
        }
    }
    fclose(fp);  
} 

Upvotes: 1

Views: 109

Answers (1)

chqrlie
chqrlie

Reputation: 144969

You cannot do this reliably by modifying the text file in place with the stream functions because you need to insert characters. You should make a modified copy of the file, then remove the original file, or rename it as a backup, and rename the new file to the original name.

Alternately, you could read the whole file in memory, perform the modification and rewrite the new contents to the file.

Upvotes: 4

Related Questions