c - getc() 用于在 C 中传入输入和读取文件

标签 c arrays input stdin getc

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

  1. 通过向其提供一个字符串(我假设像这样的文件名 < String1234455678,如果我错了,请纠正我)。
  2. 通过从某些文件读取数据。

我必须对其中的字符进行一些检查并将它们存储在数组中。但我想先学习如何使用 stdin 中的 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
}

最佳答案

这是一个示例:

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

关于c - getc() 用于在 C 中传入输入和读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29984282/

相关文章:

C 程序 : newbie trying to pass 2D string array into a function

arrays - PHP - 在数组中的第 70 个变量后丢失

C - 使用 for 循环填充数组

c++ - 捕获 ListView 控件上的键盘输入,C++

forms - 单击“后退”按钮时防止重复提交表单而不破坏页面

c - FLOPS 什么是真正的 FLOP

C编程: why are my decimals not displaying & how do I define black spaces

c++ - GTK+ 下拉菜单到工具栏项

java - 从数组中删除重复条目的程序不会删除某些条目

javascript - 元素具有 `checked` 属性但未检查?