c - Open() 系统调用不能与 DIR 目录指针结合使用

标签 c linux system-calls

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

}

最佳答案

file->d_name 只包含文件名,而不是 open(2) 需要的相对或绝对路径。这就是 open() 失败的原因(除非您的当前目录中恰好有与 DDD 目录同名的文件)。

您需要使用 snprintf() 将目录名称添加到 file->d_name 之前,例如:

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

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

关于c - Open() 系统调用不能与 DIR 目录指针结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40577651/

相关文章:

c - C 中的数组初始化有什么不同?

php - UTF-8贯穿始终

c - "creat"Unix系统调用

c - 网络库封装了 Linux 网络系统调用的哪些功能

c - C 中的字符值错误

c - 局部变量声明放置所需的 Microsoft C/C++ 编译器开关

python - C/Python API 共享数据

linux - 无法应用嵌套目录的补丁

linux - mcc -mv 在 linux 机器 R2013a 中

c - 在我的 C 代码中执行程序