With the addition of a call open(filename,O_RDONLY); for the first example, both worked great for me. I suspect your problem is caused by calling lseek(0, 100, SEEK_CUR); which requests a search on standard input. You cannot always look for a standard value - if you have:
cat file | ./my_program
Then standard input is fifo, and you cannot search. If I do this on my system, try to crash by returning -1 with the "Illegal Search" error. This may be the problem you are facing, and you may not notice, because you are not checking the return value of the search query in your example.
Please note that if you have:
./my_program < file
Then standard input is a file, and you can search for it. On my system, the search returns 100 , and the output is correct.
Here is a program that you can use to illustrate the return values:
int main(void){ int fd = 0; char blah[5]; printf("Seek moved to this position: %d\n",lseek(fd, 100, SEEK_CUR)); perror("Seek said"); printf("Then read read %d bytes\n",read(fd, blah, sizeof(blah))); printf("The bytes read were '%c%c%c%c%c'\n",blah[0],blah[1],blah[2],blah[3],blah[4]); }
And here are two performances:
$ ./a.out < text Seek moved to this position: 100 Seek said: Success Then read read 5 bytes The bytes read were '+++.-'
(These are valid bytes from position 100 in this file)
$ cat text | ./a.out Seek moved to this position: -1 Seek said: Illegal seek Then read read 5 bytes The bytes read were '# def'
(These bytes are the first 5 bytes of the file)
I also noticed that the standard input version was the one you said worked correctly. If you are having problems with the FILE * version, I suspect that the fopen() call does not work, so make sure you specify the return value from fopen() . Of course, you can always do this:
FILE *fr = stdin;
So you are reading the standard version. However, since you cannot always search for the standard version, I would recommend always opening the file if you plan to search.
Please note that you cannot search on all devices on which you can open files (although you will not have problems on most systems), so you should always check that the result is seek() to make sure that it succeeded.