【问题标题】:compile and execute c program with argument编译并执行带参数的c程序
【发布时间】:2012-10-04 05:56:48
【问题描述】:

我是C程序和linux的新手,我们如何编译和运行这个程序?

我试过gcc example.c 然后./a.out 但它给出了一个类似input file cannot be opened 的错误(我在读取方法中写了这个错误)

// example.c
int main(int argc, char *argv[])
{
    char* input = argv[1];
    read(input);

    char* output = argv[2];
    write(output);

    return 0;
} 

谢谢。

【问题讨论】:

  • 如果你成功运行了这个,那么编译成功了。请添加有关读取和写入方法的更多信息。此外,您需要在命令行上传递两个参数:./a.out FILE1 FILE2
  • 你真的应该用gcc -std=gnu99 -Wall -g example.c -o myprog编译,改进你的代码直到你不再收到警告,然后运行./myprog并学习使用gdb调试器

标签: c linux ubuntu


【解决方案1】:

您的程序不会很好地运行 - 例如,您没有为 readwrite 提供足够的参数(假设您的意思是调用 POSIX read(2)write(2),即)。

要回答您的实际问题,问题似乎是您没有提供任何论据。你需要像这样运行它:

./a.out FILE1 FILE2

FILE1 替换为输入文件的名称,将FILE2 替换为输出文件的名称。

【讨论】:

    【解决方案2】:

    首先read()write() 都接受3 个参数(只给出一个)。

    其次应该这样使用:

    int ifilehandle = open(argc[1],O_RDONLY,S_IREAD);
    int ofilehandle = open(argc[2],O_WRONLY,S_IWRITE);
    char buffer[32767];
    read(ifilehandle,&buffer,32766);
    write(ofilehandle,&buffer,32766);
    close(ifilehandle);
    close(ofilehandle);
    

    第三,a.out 应该像这样调用:

    ./a.out filename1.extension filename2.extension
    

    【讨论】:

    • +1 - 你是绝对正确的。我只是不确定“read()”和“write()”是否一定是 OP 的最佳 API。附加说明:如果 OP 使用“read()”或“write()”,他也应该#include <unistd.h>。见man read
    • 我会使用大小为 2 的缓冲区(例如 16384),并完整读取它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 2010-10-06
    • 1970-01-01
    相关资源
    最近更新 更多