【问题标题】:reading string from a file via stdin in c11通过 c11 中的标准输入从文件中读取字符串
【发布时间】:2022-08-16 16:00:42
【问题描述】:

所以我有一个 .txt 文件,我想使用 scanf() 在 c11 程序中通过 stdin 读取该文件。

该文件本质上是由一个字符串组成的多行。

例子:

hello
how
are
you

我怎么知道文件何时完成,我尝试将字符串与仅使用 eof 字符的字符串进行比较,但代码循环出错。

非常感谢任何建议。

  • scanf 返回转换的项目数和是您应该检查的内容:while(scanf(\"%31s\", buffer) == 1)。它对于非字符串输入更有用,因为它可能无法转换,但仍然比检查!= EOF 更好,后者不会捕获无法转换的输入。当scanf() 没有返回预期项目的数量时,您可以检查原因为什么,就像它是EOF。您应该始终积极检查 scanf() 是否返回正确的价值。
  • \"我尝试将字符串与仅使用 eof 字符的字符串进行比较,但代码循环出错\" -- 请提供问题的minimal reproducible example,其中包括函数main 和所有#include 指令。顺便说一句,C 中没有“eof 字符”这样的东西。宏常量EOF 是一个特殊的int 值,它不代表字符代码。

标签: c string scanf stdin


【解决方案1】:

Linux手册说(返回部分):

RETURN VALUE

   On success, these functions return the number of input items
   successfully matched and assigned; this can be fewer than
   provided for, or even zero, in the event of an early matching
   failure.

   The value EOF is returned if the end of input is reached before
   either the first successful conversion or a matching failure
   occurs.  EOF is also returned if a read error occurs, in which
   case the error indicator for the stream (see ferror(3)) is set,
   and errno is set to indicate the error.

所以测试scanf的返回值是否等于EOF

【讨论】:

  • 像 scanf()==EOF 吗?
  • @Proth:不,你应该使用这个测试:char word[40]; while (scanf("%39s", word) == 1) { /* handle word */ }
【解决方案2】:

您可以使用scanf() 读取从标准输入重定向的文件,一次一个单词,测试转换是否成功,直到无法从stdin 读取更多单词。

这是一个简单的例子:

#include <stdio.h>

int main() {
    char word[40];
    int n = 0;

    while (scanf("%39s", word) == 1) {
        printf("%d: %s\n", ++n, word);
    }
    return 0;
}

请注意,您必须在空指针之前告诉scanf() 要存储到目标数组中的最大字符数。否则,输入流中出现的任何更长的单词都会导致未定义的行为,攻击者可以尝试使用特制输入来利用漏洞。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    相关资源
    最近更新 更多