0

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

  1. 通过给它一个字符串(我假设这个文件名 < String1234455678,如果我错了,请纠正我)。
  2. 通过从某些文件中读取数据。

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

我的第一个问题是,我可以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
}
4

1 回答 1

0

这是一个示例:

#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。请参阅上面的代码以从多个文件中读取。

于 2015-05-01T09:43:55.803 回答