Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite single line in txt file

Tags:

c

I'm writing a C program that writes to a txt file. The first line is meant to be a number, that I want to update regularly. The problem I'm having is that it starts at 1, and when I reach the number 10, it overwrites the next character in the file. This is what I'm getting:

Before:

9
hello

After:

10 
ello         

I want this:

10
hello

How should I do this? Thanks in advance

PS: This is my code:

int nkv = 9;
char nkvst[10];
sprintf(nkvst, "%d\n", nkv);
fputs(nkvst, fp[3]);
fputs("hello", fp[3]);
fseek(fp[3], 0, SEEK_SET);
nkv = 10;
sprintf(nkvst, "%d\n", nkv);
fputs(nvkst, fp[3]);
like image 521
bex91 Avatar asked Nov 23 '25 15:11

bex91


1 Answers

Simple solution: store your number in the file with extra digits/spaces (at your convenience) if you know by advance which is the greatest number you want to store in the file.

For example, if your number is not going to be higher than 999999, then:

int nkv = 9;
char nkvst[10];
sprintf(nkvst, "%.6d\n", nkv);
fputs(nkvst, fp[3]);
fputs("hello", fp[3]);
fseek(fp[3], 0, SEEK_SET);
nkv = 10;
sprintf(nkvst, "%.6d\n", nkv);
fputs(nvkst, fp[3]);
like image 179
mcleod_ideafix Avatar answered Nov 26 '25 04:11

mcleod_ideafix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!