Reputation: 71
I am working on the unix system calls
.
here in my code I want to open
the file and perform lseek
operation on that file.
please look into the following code.
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
int fd;
fd = open("testfile.txt", O_RDONLY);
if(fd < 0 );
printf("problem in openning file \n");
if(lseek(fd,0,SEEK_CUR) == -1)
printf("cant seek\n");
else
printf("seek ok\n");
exit(0);
}
my output is :
problem in openning file
seek ok
My question is :
1) why open
system call is giving me the negative file descriptor ? (I have conformed that testfile.txt file is within the same directory)
2) Here I am unable to open the file(as because open()
returns me negative file descriptor) , how lseek
is successful without opening the file?
Upvotes: 1
Views: 303
Reputation: 122391
Most APIs will tell you why an error occurred, and for system calls like open()
that is achieved by looking at errno
(and using strerror()
to get a textual version of the error). Try the following (with your errors removed):
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
int main(void)
{
int fd;
fd = open("testfile.txt", O_RDONLY);
if(fd < 0 ) { // Error removed here
printf("problem in opening file: %s\n", strerror(errno));
return 1;
}
if(lseek(fd,0,SEEK_CUR) == -1) // You probably want SEEK_SET?
printf("cant seek: %s\n", strerror(errno));
else
printf("seek ok\n");
close(fd);
return 0;
}
Upvotes: 2
Reputation: 2857
In fact, you open the file successfully.
Just if(fd < 0 );
is wrong, you need to remove the ;
Upvotes: 6