The following code:
int fd;
if (fd = open("mem", O_RDONLY) == -1)
return 1;
if (lseek(fd, 0, SEEK_SET) == -1) {
char *buf = malloc(512);
buf = strerror(errno);
printf("%s\n", buf);
return 1;
}
always returns with "illegal seek" error. "mem" is executable with correct permissions. Can someone point me
in the right direction?
Try perror("error message prefix")
, much simpler.
C is grouping your open statement like this:
if (fd = (open("mem", O_RDONLY) == -1) )
So fd becomes 1 if the file fails to open, or 0 if the file is there. It must be failing, since if it opened, == -1 it would evaluate false and quit.
By unfortunate coincidence, 1 is a valid file descriptor -- standard output. It's probably a terminal or pipe, which of course can't seek.
So either parenthesize defensively, or put the assignment outside the if-statement (usually preferred).
1 Like
Thank you! I will be more careful with parentheses next time.
1 Like