I’m having a hard time figuring out why lseek doesn’t work properly. Basically all I need to do is take input from the standard input, store it into a file named “log.txt” and let the program stop as the “STOP” word is encountered.
My problem is as I try to run the program I get an lseek error: illegal seek and I don’t know why. I thought the issue was the call to lseek but if I substitute lseek(fd, 0, SEEK_END) with lseek(fd, atol(0), SEEK_END) I get a segmentation fault.
I’m just so confused, I don’t know how to proceed in order to fix this, I hope you could give your advice.
int fd;
char buffer[SIZE];
int n, cur;
if (fd = open("log.txt", O_RDWR, S_IRWXU|S_IRWXG|S_IRWXO) < 0)
{
perror("Error: open");
return 1;
}
if ((cur = lseek(fd, 0, SEEK_END)) < 0)
{
printf("Offset corrente: %d\n", (int) lseek(fd, SIZE, SEEK_CUR));
perror("Error: lseek");
return 2;
}
while ((n = read(fd, buffer, SIZE)) > 0 && (strncmp(buffer, "STOP", 4) != 0))
{
write(fd, buffer, SIZE);
}
should be
otherwise it will be parsed as
(because
<has a higher operator precedence than=); if theopen()succeeds, it will return a value that is >= 0, so the expressionopen(...) < 0will be false, sofdwill be set to 0.File descriptor 0 represents the standard input for your process. Unless you’ve redirected it, this will be a terminal device, for which seeking is illegal.