#include <stdio.h>
int main()
{
// Opens file, if file does not exist, create it. Position at end
FILE *pF = fopen("runcount.txt", "r+");
if (pF == NULL)
{
fprintf(pF, "run #1\n");
fclose(pF);
}
else
{
char runcounter[100];
fscanf(pF, "%s", runcounter);
int count = runcounter[6];
count = count + 1;
runcounter[6] = count;
fprintf(pF, "%s", runcounter);
printf("%s", runcounter);
}
return 0;
}```
#FILE handling
29 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
I'm trying to make a run counter which replaces the contents of a .txt file with +1 each time it's run
and also print it to the terminal
any ideas where i might hav egone wrong?
if (feof(pF) == 0)
I also tried that
How do i check if a file is empty?
// Opens file, if file does not exist, create it. Position at end
"r+"
Opens a file to update both reading and writing. The file must exist.
https://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm
Yes but if it doesn't exist, i want to create it
so i can't use r+
There are two cases
- If it doesn't exist, create it and add the text
- If it exists, replace 1 integer from it
So open it with w for 1.
and r+ for 2
Since none applies, i went with a+
https://stackoverflow.com/questions/13566082/how-to-check-if-a-file-has-content-or-not-using-c
You have this to check if it's empty
What ? look at the answers not the question
you can do this
FILE *pF = fopen("runcount.txt", "a+");
if (pF != NULL) {
fseek(pF, 0, SEEK_END);
int size = ftell(pF);
if (0 == size) {
}
}
WIth a+ like you said to create if it doesn't exist, then check if properly open, then check if size is 0 (empty)
Lovely i got it to work
now i just have problem replacing the number
#include <stdio.h>
int main()
{
// Opens file, if file does not exist, create it. Position at end
FILE *pF = fopen("runcount.txt", "a+");
fseek(pF, 0, SEEK_END);
long size = ftell(pF);
if (0 == size)
{
rewind(pF);
fprintf(pF, "run #1\n");
printf("run #1\n");
}
else
{
int runcounter;
fscanf(pF, "run #%d", runcounter);
runcounter = runcounter + 1;
freopen("runcount.txt", "w", pF);
fprintf(pF, "run #%d", runcounter);
}
fclose(pF);
return 0;
}
For the love of god please someone
;-;
Why isn't it replacing the number?
and incrementing it
in my else
!solved