gal gal - 2 months ago 6
C Question

Why do fseek & fputc not work in my program?

I am learning to program in C. Please explain why my program doesn't work. What is wrong? The program creates a file, writes a number into this file, and increases this number each time I run this program. The program counts how many times I have opened the file.

#include <stdio.h>

int main (void)
{
int n;
int c;
FILE* f = fopen("count_pr.bin", "a+");
if ((c=fgetc(f)) == EOF)
{
n=1;
fputc(n, f);
}
else
{
++n;
fseek(f, 0, SEEK_SET);
fputc(n, f);
}
printf ("The program was opened: %d\n", n);
fclose(f);
}

Answer

In the "a+" mode, from here

append/update: Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseek, fsetpos, rewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist.

Output operations move the position back to the end of the file. So every write you do will be at the end of the file.

In addition, you need to make changes as suggested by Klas If you want to overwrite the number each time, you should use r+ mode

read/update: Open a file for update (both for input and output). The file must exist.

There is still the issue of creating the file if it does not exist, so in that case, if the file cannot be opened in r+ mode, then you can open it in "w" or "w+" mode and only write to it.

I have updated the code below.

#include <stdio.h>
int main (void)
{
    int n;
    int c;
    FILE* f = fopen("count_pr.bin", "r+");
    if (f == NULL)
    {
        f = fopen("count_pr.bin", "w");
        if (f != NULL)
        {
           n = 1;
           fputc(n, f);
        }
        else
        {
           printf (" File Open Error");
           exit(1);
        }
    }
    else
    {    
        c=fgetc(f);
        n = c+1;
        fseek(f, 0, SEEK_SET);
        fputc(n, f);
    }
    printf ("The program was opened: %d\n", n);
    fclose(f);
}
Comments