C语言中的文件格式不可识别错误

C语言中的文件格式不可识别错误,c,ubuntu,gcc,directory,C,Ubuntu,Gcc,Directory,我一直在尝试使用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); } } 但它会返回这

我一直在尝试使用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(“”)


在这种情况下,程序可以运行。我是否在传递参数时出错。请帮助。

您将编译时参数和运行时参数混为一谈。这应分为两个步骤:

$ 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;
}
#包括
#包括
//main应该返回int
//argc是一个int,而不是指向int的指针
int main(int argc,char*argv[]){
DIR*d;
结构方向*dir;
//argv[0]是程序名,
//argv[1]是我们想要的,但只有在它存在的情况下才能得到它
如果(argc>1)d=opendir(argv[1]);
否则返回-1;
如果(d){
而((dir=readdir(d))!=NULL){
printf(“%s\n”,dir->d_name);
}
closedir(d);
}
返回0;
}

您将编译时参数和运行时参数混为一谈。这应分为两个步骤:

$ 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;
}
#包括
#包括
//main应该返回int
//argc是一个int,而不是指向int的指针
int main(int argc,char*argv[]){
DIR*d;
结构方向*dir;
//argv[0]是程序名,
//argv[1]是我们想要的,但只有在它存在的情况下才能得到它
如果(argc>1)d=opendir(argv[1]);
否则返回-1;
如果(d){
而((dir=readdir(d))!=NULL){
printf(“%s\n”,dir->d_name);
}
closedir(d);
}
返回0;
}

我尝试了这个方法,我最初的问题得到了解决。但现在在执行时它终止了,没有给出任何输出。但是桌面包含几个文件。我没有仔细查看这个问题,无法诊断代码的其余部分。编辑上面。好的,我得到了它,而不是
*argv
我给出了
argv[1]
。我的指针错误。谢谢@scfglad,你也找到了答案,但请确保你像上面一样添加了错误检查,否则如果你尝试在没有参数的情况下运行程序,你会得到seg错误。我尝试了这个,我最初的问题解决了。但现在在执行时,它终止了,没有给出任何输出。但桌面包含几个文件。我没有仔细研究这个问题,无法诊断代码的其余部分。编辑上面。好的,我得到了它,而不是
*argv
我给出了
argv[1]
。我的指针错误。谢谢@scfglad,你也找到了答案,但请确保你像上面一样添加了错误检查,否则,如果你尝试在没有参数的情况下运行程序,你会得到seg错误。