【问题标题】:File format not recognized error in CC中的文件格式无法识别错误
【发布时间】:2016-05-25 23:22:00
【问题描述】:

我一直在尝试使用 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("&lt;path of the file here&gt;");

在这种情况下程序可以工作。我在传递参数时做错了什么吗?请帮忙。

【问题讨论】:

    标签: c ubuntu gcc directory


    【解决方案1】:

    您混淆了编译时参数和运行时参数。这应该是两个步骤:

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

    【讨论】:

    • 我试过这个,我最初的问题已经解决了。但是现在在执行时它会终止而不给出任何输出。但是桌面包含几个文件。
    • 我没有仔细研究这个来诊断你的代码的其余部分。在上面编辑。
    • 好的,我知道了,而不是*argv,我给了argv[1]。我的指针错误。谢谢@scf
    • 很高兴您也发现了这一点,但请确保您像我在上面所做的那样添加错误检查,否则如果您尝试不带参数运行程序,则会出现段错误。
    猜你喜欢
    • 2021-01-13
    • 1970-01-01
    • 2011-05-25
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多