如果没有给出参数

如果没有给出参数

本文介绍了如果没有给出参数,如何从argv或stdin中的文件中读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,可以计算彩票(该彩票位于file.txt中),并将中奖彩票写入另一个文件中.我有一个子函数叫做Evaluation_tickets(file,lottery_numers,Winner ....)

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....)

在shell中,我写:./program arg1 arg2...(arg1,arg2是文本文件,即file.txt)

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

但是现在,我想做./program < file.txt.问题是我不知道如何通过标准输入来接收信息,因为我不知道如何发送Evaluate_tickets的参数文件".

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.

推荐答案

定义流指针FILE *fp;以读取到输入文件:

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

  • 如果要从文件读取输入,请使用fp = fopen(filename, "r");打开文件,并在使用fclose(fp);处理后关闭流.
  • 如果要从标准输入中读取输入,只需分配fp = stdin;而不是使用fopen().
  • 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().

这是一个简短的示例:

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

以下是使用更简洁方法的相同示例,将stdin或打开的FILE指针传递给ad hoc函数.注意它如何处理所有命令行参数:

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

这篇关于如果没有给出参数,如何从argv或stdin中的文件中读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-21 02:37