Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File program - fseek isnt working

Tags:

c

file

fseek

I'm having trouble making this fseek() function work in my code. The text I wrote just doesn't start at the point I indicate and I don't know why. It should start writing from the \n and it just overwrite all the text file. Even if I open it with a it just doesn't go where I command through the parameters.

   fclose(file);
    FILE *file_a = fopen("ex6.txt", "w");

    fseek(file_a, -1, SEEK_END);

    puts("Write text to add:");
    while((letter = getchar()) != '\n')
    {
        fputc(letter, file_a);
    };

What is happening? Why doesnt this work?

like image 310
Telmo Vaz Avatar asked Oct 14 '25 04:10

Telmo Vaz


1 Answers

Navigating to absolute only works when the file is opened in binary mode. When it's opened in text mode, fseek() cannot navigate to absolute positions in a file besides 0 (the start of the file), and trying to do so will result in undefined behaviour. You can, however, navigate to references in the file returned by ftell(). The reason for this is due to the handling of certain characters by some operating systems; some implementations allow it but POSIX doesn't mandate it.

I know you solved the issue in the comments, this is just for closure.