【问题标题】:Open() system call doesnt work in combination with DIR directory pointerOpen() 系统调用不能与 DIR 目录指针结合使用
【发布时间】:2016-11-13 19:02:36
【问题描述】:

Open() 系统调用在此代码中不起作用。但是,如果不与目录指针组合使用,它们可以正常工作。在这里,我使用 file->d_name 访问字符串基地址以打开文件,但它不起作用并打印错误。

#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<dirent.h> 
#include<unistd.h>
#include<sys/dir.h>

int main()
{
  DIR* d=opendir("DDD");
  struct dirent* file;
  int fd;
  char WBUFFER[]="IO OS system calls\n";
  char RBUFFER[100001];

  while((file=readdir(d))!=NULL)
  if(strlen(file->d_name)>=10)
    {
      if((fd=open(file->d_name,O_RDWR,0))==-1)
        printf("error\n");
      read(fd,RBUFFER,101);
      printf("%s",RBUFFER);
      close(fd);   
    }
  else if(strlen(file->d_name)>=3)
    { 
      if((fd=open(file->d_name,O_RDWR,0))==-1)
      printf("error2\n");
      write(fd,WBUFFER,50);
      close(fd);
    }

}

【问题讨论】:

    标签: c linux system-calls


    【解决方案1】:

    file-&gt;d_name 仅包含文件名,而不是 open(2) 所需的相对或绝对路径。这就是open() 失败的原因(除非您在当前目录中碰巧有与DDD 目录同名的文件)。

    您需要使用snprintf() 将目录名称添加到file-&gt;d_name,例如:

    char buf[PATH_MAX];
    snprintf(buf, sizeof buf, "DDD/%s", file->d_name);
    

    并在您的open() 调用中使用buf

    【讨论】:

      【解决方案2】:

      所以 dirent->d_name 只包含文件名,而不是路径。如果您使用的是现代 Linux 或 POSIX-2008 兼容系统,那么做您正在做的事情的一种不错的(例如,无种族)方式类似于(缩短的半代码,填写留下的详细信息)读者练习):

      
      int dfd = open("DDD", ...);
      DIR *d = fdopendir(dfd);
      ...
      while ((file = readdir(d)) != NULL) {
          int fd = openat(dfd, file->d_name, ...);
          ...
      }
      

      【讨论】:

        猜你喜欢
        • 2010-10-10
        • 2015-06-02
        • 2021-06-21
        • 1970-01-01
        • 2015-01-06
        • 1970-01-01
        • 2019-05-10
        • 1970-01-01
        • 2012-10-21
        相关资源
        最近更新 更多