【问题标题】:Reading chars from multiple files in C从C中的多个文件中读取字符
【发布时间】:2015-05-04 20:48:41
【问题描述】:

我正在尝试读取不同文件中的所有字符。例如,通过调用myprogram < file1 file2

我的方法如下:

void do_read(FILE * file){
char ch;

    while (ch != EOF) {
        ch = getc(file);


        printf("%c\n", ch);
}

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

    if (argc < 1) {
        //Error. No file given
printf("Error");
    }
    else {
        // cycle through all files in command line arguments and read them
        for (i=1; i < argc; i++) {
            if ((fp = fopen(argv[i], "r")) == NULL) {
                printf("Failed to open file.\n");
            }
            else {
                do_read(fp);
                fclose(fp);
            }
        }
    }

    return 0;
}

但每当我尝试以myprogram &lt; file1(只有1个参数)运行它时,它不会输出任何内容。甚至没有printf("Error")

谁能帮我修复我的代码?我究竟做错了什么?有更好的方法吗?

非常感谢您提前提供的帮助!

【问题讨论】:

  • 第一个参数是程序名,你永远不会有argc &lt; 1
  • 感谢您的观察。将更正我的代码!
  • 加上char ch; while (ch != EOF) {ch还没有定义,那么你希望while (ch != EOF)做什么?

标签: c file file-io stdin


【解决方案1】:

myprogram &lt; file1 本质上是cat file1 | myprogram 的简写,也就是说,您的程序需要读取标准输入来获取该文件的内容。你想要的调用是myprogram file1 file2

此外,您的 do_read 函数已损坏,因为它甚至会在 EOF 时打印字符。与其在获得之前检查,不如检查何时获得:

void do_read(FILE * file){
    char ch = '\0';

    while (ch != EOF) {
        ch = getc(file);
        printf("%c\n", ch);
    }
}
/* Becomes: */
void do_read(FILE * file){
    char ch = '\0';

    while ((ch = getc(file)) != EOF) {
        printf("%c\n", ch);
    }
}

【讨论】:

  • @CesarA:注意这个答案的第一句话。您必须在命令行上使用&lt; 调用程序。这会将标准输入重定向到第一个文件,但由于程序确实读取标准输入,因此会跳过该文件。
  • 你是对的!顺便说一句......你碰巧知道如何将数组的所有元素设置为空吗?就像在我使用它们后删除它的值一样!感谢您的帮助
  • @CesarA 1. 将数组元素设置为 null '删除项目' - 可能在 Java 中会这样做,但在 C 中不会。 2. 不要添加cmets 中的请求;而是提出一个新问题。
  • 使用int ch 作为getch() 返回257 个不同的值。尝试将 257 个不同值中的 1 个存储到 char 会破坏某些内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-08
  • 1970-01-01
  • 2014-01-21
  • 2012-02-04
  • 2017-09-06
  • 1970-01-01
相关资源
最近更新 更多