Command Line Arguments and File Input

社会主义新天地 提交于 2020-01-07 06:37:21

问题


I had a terrible time with file input from command line arguments last semester and I need to utilize it for an exercise that I am working on. I have coded a simple shell just to get it working:

prob_5.c

#include <stdio.h>

int main(int argc, char *argv[]) {
int i;
FILE *fp;
int c;

for (i = 1; i < argc; i++) {
    fp = fopen(argv[i], "r");

    if (fp == NULL) {
        fprint(stderr, "cat: can't open %s\n", argv[i]);
        continue;
    }

    while ((c = getc(fp)) != EOF) {
        putchar(c);
    }

    fclose(fp);
}

return 0;
}

I can't seem to remember what the commands are for invoking my program from the command line. I have tried:

gcc -o prob_5 -g -ansi prob_5.c

I have reformatted my computer since last semester, so perhaps I am missing a System Path?


回答1:


It looks like your program just expects one argument: the file name. You also have to compile it first.

$ gcc -o prob_5 prob_5.c
$ ./prob_5 input_file.txt

If it is not compiling, then you have another issue. What is returned when you execute gcc?



来源:https://stackoverflow.com/questions/7437502/command-line-arguments-and-file-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!