我一直在尝试使用以下 c 代码打开目录的内容。
#include<stdio.h>
#include<dirent.h>
main(int *argc,char *argv[]){
DIR *d;
struct dirent *dir;
d=opendir(*argv);
if(d){
while((dir = readdir(d))!= NULL){
printf("%s\n",dir->d_name);
}
closedir(d);
}
}
然后我执行这样的命令:
gcc test.c ~/Desktop
但它返回的是这样的:
/usr/bin/ld: cannot find /home/cse-swlab5/Desktop: File format not recognized collect2: ld returned 1 exit status
我没有找到原因。我也试过放置
d=opendir("<path of the file here>");
在那种情况下,程序可以运行。我是否在传递参数时做错了什么。请帮忙。
最佳答案
您混淆了编译时参数和运行时参数。这应该是两个步骤:
$ gcc test.c
$ ./a.out ~/Desktop
代码中还有其他一些错误。工作版本如下:
#include <stdio.h>
#include <dirent.h>
// main should return int
// argc is an int, not a pointer to an int
int main(int argc,char *argv[]){
DIR *d;
struct dirent *dir;
//argv[0] is the program name,
//argv[1] is what we want, but can only get it if it's there
if (argc > 1) d=opendir(argv[1]);
else return -1;
if(d){
while((dir = readdir(d))!= NULL){
printf("%s\n",dir->d_name);
}
closedir(d);
}
return 0;
}
关于c - C中的文件格式无法识别错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35402767/