【问题标题】:unable to `open` the file , but `lseek` is done without error无法“打开”文件,但“lseek”完成且没有错误
【发布时间】:2013-09-04 14:33:33
【问题描述】:

我正在处理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 &lt; 0 );
  • 整个前提是有缺陷的。由于多余的分号而出错。
  • 你只是假设文件描述符是负的。如您所见,没有证明的假设是危险的。 ;-)

标签: c++ c unix


【解决方案1】:

其实你打开文件成功了。

只是if(fd &lt; 0 );是错误的,你需要删除;

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 这个你可能知道,但是printf()strerror()可以被perror()抽象出来。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 2014-11-23
    • 2021-10-16
    • 2013-03-21
    • 2014-03-24
    相关资源
    最近更新 更多