kadina
kadina

Reputation: 5376

why SEEK_SET flag is not working as expected

I tried to do lseek() on a file which is opened in write mode as below. But it is not working as expected.

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>

main()
{
    int fd = open("/local/sandbox/.C/mytest", O_WRONLY | O_APPEND);

    if(fd == -1)
    {
        printf("\nFailed to opne file in write mode\n");
        return -1;
    }

    lseek(fd, 2, SEEK_SET);
    write(fd, "OK", 2);
    write(fd, "AAAAAAAA", 3);

    close(fd);
}

'mytest' file is already existed with the content "Hi, How are you". I thought after executing the program, my test will contain 'HiOKAAA, How are you". But instead it is writing "OKAAA" at the end. Is it because of O_APPEND flag? But even, I am using lseek() to change the file offset to '2' only. Can any one please let me know why it is failing?

Upvotes: 0

Views: 362

Answers (1)

Barmar
Barmar

Reputation: 780871

Yes, the O_APPEND option is causing this. From the POSIX specification of open:

O_APPEND

If set, the file offset shall be set to the end of the file prior to each write.

If you want to be able to write to arbitrary locations in the file, don't use O_APPEND mode.

Upvotes: 1

Related Questions