【问题标题】:getc() for passed in input and file reading in Cgetc() 用于在 C 中传入的输入和文件读取
【发布时间】:2015-05-01 09:13:27
【问题描述】:

我必须用 C 语言开发一个可以有两种输入的程序。

  1. 给它一个字符串(我假设这个文件名
  2. 通过从某些文件中读取数据。

我必须对其中的字符进行一些检查并将它们存储在一个数组中。但我想先学习如何使用标准输入中的getc()

我的第一个问题是,我可以在这两种情况下都使用getc() 吗?

我想遍历提要行/文件中的每个字符,并且我假设代码看起来像这样:

char Array1[];
char charHolder;


//If the file/feed has chars (!NULL), execute
if ((charHolder = getchar())!=NULL){
    //Do something
    //Do some more
    //Finally append to Array1
    Array1[] = charHolder;
}

上面的代码可能存在一些问题。我想知道这种插入在 C 中是否有效(没有指定索引,它只会将值推到数组末尾)。另外,我从http://beej.us/guide/bgc/output/html/multipage/getc.html 读到getc(stdin)getchar() 是完全等价的。我只是想仔细检查一下这确实是真的,并且任何一个函数都适用于我必须读取数据(从文件中并为我的程序提供字符串)的两种情况。

另外,我想知道如何实现从多个文件中读取字符。假设我的程序是否作为 programName file1 file2 执行。

感谢您的宝贵时间和帮助!

干杯!

编辑 1:


我还想知道如何检查字符何时从文件/字符串提要结束。两种情况我都应该使用 EOF 吗?

例子:

while ((charHolder = getchar()) != EOF){
    //code
}

【问题讨论】:

  • 如果charHolderint 类型,while ((charHolder = getchar()) != EOF){ 很好。 getchar() 返回一个在unsigned charEOF 范围内的值。这些通常有 257 个不同的值不能唯一地存储在 char 中。

标签: c arrays input stdin getc


【解决方案1】:

这是一个示例:

#include <stdio.h>

void do_read(FILE * file, int abort_on_newline) {
    char ch;

    while (1) {
        ch = getc(file);
        if (ch == EOF) {
            break;
        }
        if (abort_on_newline && ch == '\n') {
            break;
        }
        printf("%c", ch);
    }
}

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

    if (1 == argc) {
        // read input string from stdin, abort on new line (in case of interactive input)
        do_read (stdin, 1);
    }
    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,0);
                fclose(fp);
            }
        }
    }

    return 0;
}

像这样使用它:

  1. 从标准输入读取:echo youstring |你编程,或者刚开始 你的程序从用户那里获取输入
  2. 从文件中读取 yourprogram yourfile1 yourfile2 ...

是的,你可以在这两种情况下使用 getc,是的,你应该在这两种情况下检查 EOF,除了交互式输入。如果是二进制文件,您还需要使用 feof 函数来检查 EOF。请参阅上面的代码以读取多个文件。

【讨论】:

  • 是否每个字符都会执行整个代码?
  • 不。要对每个字符执行某些操作,请替换 "printf("%c", ch);"在 do_read 函数中,您需要使用“ch”。
  • 我正在尝试从字符串中附加每个字符,例如“ASD”,在返回 0 之前,我创建了一个打印数组的方法...但是数组打印了 3 次.. . 你知道为什么吗?
  • 看看这个关于“附加到数组”的答案:stackoverflow.com/questions/10279718/append-char-to-string-in-c
  • 使用int ch。否则,如果 char 未签名,if (ch == EOF) 将永远不会为真。当char 被签名并且ch ==255 时,它可能是错误的。
猜你喜欢
  • 2021-10-29
  • 2020-09-21
  • 2023-04-04
  • 1970-01-01
  • 2021-04-08
  • 1970-01-01
  • 2021-05-07
  • 1970-01-01
  • 2017-01-25
相关资源
最近更新 更多