c - C中的文件格式无法识别错误

标签 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);
}

} 

然后我执行这样的命令:

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/

相关文章:

c - 如何确保用户输入是唯一的

c - 如何让 callgrind 转储源代码行信息?

ruby - 如何在 Ubuntu 14.04 上安装 Ruby 2.1.4

c++ - [错误]未分配正在释放的指针

c - 如何在不选择的情况下检查非阻塞套接字超时

c - SDL2/C 中放慢矩形速度

web-services - 我可以在 linux 机器上安装时指定 rabbitmq-server 版本吗?

java - 使用 Forge 启动 Minecraft 1.12.2 时出现错误 : Could not find or load main class net. minecraft.launchwrapper.Launch

c++ - 应用程序段错误,仅当使用 MinGW 在 Windows 上编译时

C 结构初始化完成 "recursively"