我的程序有问题。 我需要获取文件夹中的文件名并将其放入变量中。 我试过了:
#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部分:
- fileName 类型应与分配的结构成员相同。
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/