How to read from files in argv or stdin if none are given?

一世执手 提交于 2020-08-17 11:06:30

问题


I have a program that calculates a lottery tickets (this tickets are in a file.txt), and writes the winners tickets in another file. I have a subfunction called evaluate_tickets(file, lottery_numers, winner....)

In shell I write: ./program arg1 arg2... (arg1, arg2 are text files i.e. file.txt)

But now, I want to do ./program < file.txt. The problem is that I don't know how to send the parameter "file" of evaluate_tickets because I receive information by stdin.


回答1:


Define a stream pointer FILE *fp; to read to input file:

  • If you want the input to be read from a file, use fp = fopen(filename, "r"); to open the file and close the stream after processing with fclose(fp);.
  • If you want the input to be read from standard input, just assign fp = stdin; instead of using fopen().

Here is a short example:

#include <stdio.h>

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

    if (argc > 1) {
        fp = fopen(argv[1], "r");
        if (fp == NULL) {
            fprintf(stderr, "cannot open %s\n", argv[1]);
            return 1;
        }
    } else {
        fp = stdin; /* read from standard input if no argument on the command line */
    }

    lines = 0;
    while ((c = getc(fp)) != EOF) {
        lines += (c == '\n');
    }
    printf("%d lines\n", lines);
    if (argc > 1) {
        fclose(fp);
    }
    return 0;
}

Here is the same example with a cleaner approach, passing stdin or an open FILE pointer to an ad hoc function. Note how it handles all command line arguments:

#include <stdio.h>

void count_lines(FILE *fp, const char *name) {
    int c, lines = 0;
    while ((c = getc(fp)) != EOF) {
        lines += (c == '\n');
    }
    printf("%s: %d lines\n", name, lines);
}

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

    if (argc > 1) {
        for (int i = 1; i < argc; i++) {
            fp = fopen(argv[i], "r");
            if (fp == NULL) {
                fprintf(stderr, "cannot open %s\n", argv[i]);
                return 1;
            }
            count_lines(fp, argv[i]);
            fclose(fp);
        }
    } else {
        /* read from standard input if no argument on the command line */
        count_lines(stdin, "<stdin>");
    }
    return 0;
}


来源:https://stackoverflow.com/questions/49992400/how-to-read-from-files-in-argv-or-stdin-if-none-are-given

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