c - 在 C 程序中使用 .txt 接收输入

标签 c input

我什至不确定是否从这里开始,但本质上我不想使用用户输入来运行我的程序,而是想使用 .txt 来接收和存储我的输入。

例如,.txt 文件显示如下:
1 2 3
5 6
8 9 10

如何打开此 .txt 文件并将每个单独的数字存储为程序中的变量?

最佳答案

所有这些都假设您提供的示例输入。调整到不同的输入排列留给读者作为练习......

几乎是最简单的程序(假设您运行:./myprogram < myfile.txt)

#include <stdio.h>

int main ( void ) {

    int a, b, c, d, e, f, g, h;          /* terrible variable names */

    scanf("%d %d %d", &a, &b, &c);
    scanf("%d %d", &d, &e);
    scanf("%d %d %d", &f, &g, &h);

    return 0;
}

下一步,从命名文件中读取:

int main ( void ) {

    FILE * fp;
    int a, b, c, d, e, f, g, h;          /* terrible variable names */

    fp = fopen("myfile.txt", "r");
    if (fp == NULL) {
        perror("open failed");
        return 1;
    }
    fscanf(fp, "%d %d %d", &a, &b, &c);
    fscanf(fp, "%d %d", &d, &e);
    fscanf(fp, "%d %d %d", &f, &g, &h);

    fclose(fp);
    return 0;
}

注意这些变化。改进这一点的下一步是从命令行获取文件名。

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

    FILE * fp;
    int a, b, c, d, e, f, g, h;          /* terrible variable names */
    char * filename;

    if (argc > 1) filename = argv[1];
    else {
         fprintf(stderr, "please supply an input filename on the command line\n");
         return 2;
    }
    fp = fopen(filename, "r");
    /* and then continues as in the version above... */
}

再次注意更改。

关于c - 在 C 程序中使用 .txt 接收输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25813042/

相关文章:

创建一个充满随机唯一数字的数组

c - gcc 的正确选项顺序是什么?该顺序的重要性是什么?

c - 如何更正 Well-Known Binary 格式的字节顺序?

java - 不断收到 "catch without try"错误

javascript - 当我想创建多个输入类型时选择文件时出现问题 = 'file'

c++ - 如何在我的终端上隐藏我的输入?

c - 在 OS X Mavericks 上使用 -O3 编译时出现 Getopt 代码段错误

捕捉 WM_DEVICECHANGE

javascript - 输入类型 "time"没有小时,mm :ss format

javascript - 如何为 document.activeElement 设置文本值?