Search code examples
cfilefopenfseek

fseek function is not working after fopen(argv[1], "ab")


When I opened the file with "wb" option, fseek worked well. But fseek function is not working well after fopen(argv[1], "ab").

Is there any problem in my code?

Here is the code.

student.h
struct student {
  int id;
};

main.c
#define START_ID 1201001
struct student rec;
FILE *fp = fopen(argv[1], "rb");
if(fp==NULL) {
    fp=fopen(argv[1], "wb");
} else {
    fclose(fp);
    fp=fopen(argv[1], "ab");
}
fseek(fp, (rec.id-START_ID)*sizeof(sec), SEEK_SET);

Solution

  • The problem is that fseek is not supposed to work when a file is opened with the "a" attribute. See here:

    append: Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist.

    To get round the problem, try using the "a+" attribute:

    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.