c - 不使用 fread、fopen、fscanf、fgets 从文件读取字符到行尾
问题描述
这是文件内容:
你好 如何 是 你
我必须阅读每一行的行尾,因为我必须单独处理所有这些行。我不能使用fread
, fopen
, fscanf
, fgets
。
解决方案
您可以重新打开stdin
并freopen
使用getc
从文件中读取字节。
如果不允许来自的任何流函数<stdio.h>
,请使用低级 POSIX 函数open
和read
. 手册页可在线获取,网址man 2 open
为man 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;
}
推荐阅读
- r - 从使用 shinyDirChoose 加载的文件夹中渲染图像以进行交互式显示
- css - 缩放 SVG clipPath 并保持图像的纵横比
- c++ - 静态链接 MSVC 库,动态链接 Qt
- javascript - 如何使 React 组件更改全局 CSS
- python - Pandas.DataFrame.resample MultiIndex 的内部级别
- android - 在 android studio 中从互联网上获取真实的日期和时间
- python - 如何在 PyQt5 GUI 中制作快速 matplotlib 实时绘图
- selenium - aws lambda:如何修复“geckodriver”可执行文件需要在 PATH 中”
- c# - 最优最大行驶距离问题
- javascript - 有没有办法在动态的日子里添加按钮或弹出消息