1
int main(int argc, char *argv[]) 

{

int i, j, count;
int f1;
char buf[16];
f1 = open(argv[1], O_RDWR | O_APPEND);
if(f1 == -1)
    perror("open failed");

if(lseek(f1, 0, SEEK_SET) == -1)
    printf("lseek failed\n");


while(count = read(0, buf, 16)) {
    write(f1, buf, count);
}

close(f1);
return 0;
}

This is my code. It opens files given as an argument and should write everything from console at the start of the file. The file is opened in append mode and then lseek is used to move the descriptor to the start. There is no change in the value of f1 not it prints lseek failed.

cdomination
  • 605
  • 1
  • 7
  • 25
sasha00
  • 23
  • 1
  • 1
  • 5

1 Answers1

2

Because if the file opened as O_APPEND mode, every time of calling of write(), the offset pointer moved to the End of file for handling the atomic operation.

This used to the purpose of many process appending "text" into the file.(eg log file) as only from at end of the file.

So try to change code as:

open file only in O_RWONLY flag (if need to seek to EOF use the lseek()).

without using O_APPEND flag in open(),The write() didn't move the offset to the EOF automatically on each calling.