4

So I'm trying to learn C file IO operations from a snippet from the university. My problem is that SEEK_END doesn't work as I expect it to work.

Let met give you more details:

input.txt:

abcd-abcd-abcd

code:

int fd, fdr, l1, l2, wb1, wb2;
char buf[25];

fd = open("input.txt", O_WRONLY);
fdr = open("input.txt", O_RDONLY);

l1 = lseek(fd, -3, SEEK_END);
wb1 = write(fd, "xy", 2);

l2 = lseek(fd, 4, SEEK_SET);
write(fd, "12", 2);

lseek(fdr, 0, SEEK_SET);
wb2 = read(fdr, buf, 20);
write(1, buf, wb2);

My problem is writing "xy". I expect the output to be

abcd12bcd-axyd

Instead it is

abcd12bcd-abcd

Why the "xy" is not written?

Charles
  • 50,943
  • 13
  • 104
  • 142
  • Works here (gcc (Debian 4.4.5-8) 4.4.5) as expected, writing out `abcd12bcd-axyd` to the console. – alk Nov 20 '13 at 09:07
  • If look the file size of `input.txt` (using the shell or any file browser) what do you get before and after you ran the program? `14`? – alk Nov 20 '13 at 09:21
  • On which platform/OS do you experience this behaviour? – alk Nov 20 '13 at 09:25

2 Answers2

0

Close the write only file (or sync data to disk) before reading the file from another handle.

In your case, data is written to file, but not synced to disk yet. So when 2nd handle tries to read the data, it gets old stale data.

int fd, fdr, l1, l2, wb1, wb2;
char buf[25];

fd = open("input.txt", O_WRONLY);
fdr = open("input.txt", O_RDONLY);

l1 = lseek(fd, -3, SEEK_END);
wb1 = write(fd, "xy", 2);

l2 = lseek(fd, 4, SEEK_SET);
write(fd, "12", 2);

close(fd); 

lseek(fdr, 0, SEEK_SET);
wb2 = read(fdr, buf, 20);
write(1, buf, wb2);
Rohan
  • 52,392
  • 12
  • 90
  • 87
0

You need to sync data to the disk before reading it again. Because data is not written at the time of your read. you need to close file before read.

Chinna
  • 3,930
  • 4
  • 25
  • 55