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]);
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With