c - file->d_name 到 C 中的变量中

标签 c variables filenames

我的程序有问题。 我需要获取文件夹中的文件名并将其放入变量中。 我试过了:

#define _POSIX_SOURCE
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#undef _POSIX_SOURCE
#include <stdio.h>

int main()
{
    DIR *dir;
  struct dirent *file;
  char fileName;
  dir = opendir("../../incoming");

    while ((file = readdir(dir)) != NULL)
    printf("  %s\n", file->d_name);
    fileName = file->d_name;
    printf(fileName);
    closedir(dir);
    return 0;
}

谢谢

最佳答案

不太清楚你想要什么,我更愿意认为你想将文件名读入变量“fileName”,然后处理该变量...... 正确2部分:

  1. fileName 类型应与分配的结构成员相同。
  2. while 循环......

    int main(){
      DIR *dir;
      struct dirent *file;
      char fileName[255];
      dir = opendir("../../incoming");
        while ((file = readdir(dir)) != NULL)
        {
            printf("  %s\n", file->d_name);
            strncpy(fileName, file->d_name, 254);
            fileName[254] = '\0';
            printf("%s\n", fileName);
        }
        closedir(dir);
    return 0;
    }
    

关于c - file->d_name 到 C 中的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22160807/

相关文章:

java - 为什么我的错误检查不起作用?

python - Windows 上 os.path.normcase 的反转

C 字符串和十六进制字符

c - 使用大数时,函数 pow() 无法正常工作?

c - DNS session 的结构是什么?

javascript - 动态查找变量

java - 导入包并使用实例变量

linux - 在 bash 中更改变量输出

php - 如何创建具有特定名称的临时文件

c++ - 如何使用 libqrencode 编译项目?