繁体   English   中英

在 C 中通过 STDIN 读取文件

[英]Reading a file through STDIN in C

我正在尝试在cmd中运行以下命令:

gcc my_mainFile

然后运行以下命令:

a.exe 2 < file.ppm

基本上它所做的是查看值2 ,基于该值调用特定函数,并使用ppm文件中的内容。 但是,我不知道如何访问此文件本身。 我需要使用scanf()来读取文件,但我没有明确的格式。

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    if(*argv[1] - '0' == 2){
        //Open and read contents of the file
    }
}

许多 Linux 实用程序允许您将要读取的文件名作为第一个参数传递或默认从stdin读取。 这允许您从给定的文件名中读取,或者将来自另一个进程的输出通过管道传输或重定向到您在stdin上的代码。 要实现替代方案,您可以利用stdin的类型FILE*并简单地检查是否提供了文件名参数以供读取(如果是,则打开并从该文件读取),或者默认情况下从stdin读取。

例如:

#include <stdio.h>

#define MAXC 1024   /* if you need a constant, #define one (or more) */

int main (int argc, char **argv) {

    char buf[MAXC]; /* buffer to hold entire line (adjust MAXC as needed) */
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    while (fgets (buf, MAXC, fp)) {                 /* read each line of input */
        int a, b;                                   /* example variables */
        if (sscanf (buf, "%d %d", &a, &b) == 2) {   /* parse/validate values */
            /* do what you need with your values */
            printf ("a: %d    b: %d\n", a, b);
        }
    }

    if (fp != stdin)   /* close file if not stdin */
        fclose (fp);

    return 0;
}

上面, fgets()用于确保每次读取都消耗完整的输入行,防止在输入流中留下未读的杂散字符,这会导致下次尝试读取时读取失败(或无限循环)。 该行所需的任何值都使用sscanf进行解析。 这避免了新 C 程序员在理解如何检测和正确处理匹配输入失败之前尝试直接使用scanffscanf读取的大量陷阱,这些失败是由于格式说明符和输入之间的不匹配,或者之前耗尽输入指定的转换发生。

例子

stdin上的管道输入:

$ printf "1 2\n3 4\n" | ./bin/readfileorstdin
a: 1    b: 2
a: 3    b: 4

示例输入文件

$ cat dat/2x2.txt
2 4
3 5

直接或在stdin上处理文件

直接读取文件:

$ ./bin/readfileorstdin dat/2x2.txt
a: 2    b: 4
a: 3    b: 5

stdin上重定向:

$ /bin/readfileorstdin < dat/2x2.txt
a: 2    b: 4
a: 3    b: 5

您不必这样做,您可以直接从stdin读取并避免检查是否给出了文件名——但这种方法只需几行额外的代码就可以为输入处理提供很多便利和灵活性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM