gpt4 book ai didi

c - 从 stdin 读取文本(不带 fopen)

转载 作者:行者123 更新时间:2023-11-30 21:27:56 25 4
gpt4 key购买 nike

我正在尝试编写一些代码来从标准输入逐个字符、逐行读取我的文本文件,而不使用fopen。我需要 42 行,最多 100 个字符。

帮助我让它工作并向我解释它是如何工作的。谢谢!

int main()                                                      
{
char str[100];

fgets(str, sizeof(str), stdin);
fputs(str, stdout);
return 0;}

最佳答案

without using fopen

如果允许开放。为什么不将它与 read 一起使用?该解决方案将允许您逐字符读取。

int main(void)
{
int file_descriptor = open("./path", O_RDWR); /* Open with read/write */
char text_block[10]; // Random size

read(file_descriptor, text_block, 1); /* This will read 1 characters
from the file */

/* Then do what you want with the char readed. */
}

考虑到这个解决方案,以下是一个可行的过程:

  1. 使用stat()函数了解文件的大小(阅读手册)
  2. 使用与上述相同的过程,但不是读取 1 个字符,而是读取文件的大小
  3. 除最后一行外,每一行均由 '\n' 分隔。只需用它来将您完全阅读的文件分成几行

我猜这是为了做作业...这段代码有一个错误并且在你找到它之前不会编译。这意味着在网上搜索手册并阅读它。

关于c - 从 stdin 读取文本(不带 fopen),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46939872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com