首页 > 解决方案 > 不使用 fread、fopen、fscanf、fgets 从文件读取字符到行尾

问题描述

这是文件内容:

你好
如何
是
你

我必须阅读每一行的行尾,因为我必须单独处理所有这些行。我不能使用fread, fopen, fscanf, fgets

标签: c

解决方案


您可以重新打开stdinfreopen使用getc从文件中读取字节。

如果不允许来自的任何流函数<stdio.h>,请使用低级 POSIX 函数openread. 手册页可在线获取,网址man 2 openman 2 read

#include <stdio.h>

int main() {
    if (freopen("myfile.txt", "r", stdin) != NULL) {
        char buf[1000];
        int c;
        size_t n;
        for (n = 0; n < sizeof(buf) - 1; n++) {
            c = getc(stdin);   // or c = getchar();
            if (c == EOF)
                break;
            buf[n] = c;
        }
        buf[n] = '\0';
        // the file contents are in `buf`, handle these lines as appropriate
    }
    return 0;
}

推荐阅读