Telmo Vaz
Telmo Vaz

Reputation: 57

File program - fseek isnt working

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?

Upvotes: 4

Views: 3817

Answers (1)

user2395375
user2395375

Reputation:

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.

Upvotes: 3

Related Questions