繁体   English   中英

无法“打开”文件,但是“ lseek”完成但没有错误

[英]unable to `open` the file , but `lseek` is done without error

我正在进行unix system calls 在我的代码中,我想open文件并对该文件执行lseek操作。 请查看以下代码。

#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);

} 

我的输出是:

   problem in openning file 
   seek ok

我的问题是:

1)为什么open系统调用会给我负面文件描述符? (我已确认testfile.txt文件位于同一目录中)

2)在这里我无法打开文件(因为open()返回否定文件描述符), lseek如何成功而不打开文件?

实际上,您成功打开了文件。

只是if(fd < 0 ); 是错误的,您需要删除;

大多数API会告诉您为什么会发生错误,对于通过调用errno (并使用strerror()获取错误的文本版本strerror()实现的系统调用(如open() )。 请尝试以下操作(消除了错误):

#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;

} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM