c - 读取不一致的文件

标签 c file-io scanf

C 中的哪些文件读取器可以处理读取不一致的文件?有时文件是“字号”,有时只是“字”。像这样。

bob 456
echo
cat 
dog 1101
peacock 300

这是我用 fscanf 尝试的。我很惊讶它起作用了。我认为 fscanf 不喜欢不一致的文件。有什么需要担心的吗?我知道如果你不小心 fscanf 有非常糟糕的副作用。

while (fscanf(pFile, "%s %d",  nam, &val) !=EOF)
{
    //my work
}

最佳答案

您需要仔细阅读 fscanf 的文档 :

Upon successful completion, these functions shall return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure. If the input ends before the first matching failure or conversion, EOF shall be returned. If a read error occurs, the error indicator for the stream is set, EOF shall be returned, and errno shall be set to indicate the error.

我会做这样的事情:

while (TRUE) {
    int matched = fscanf(pFile, "%s %d", nam, &val);

    if (matched == 2) {
        // nam and val are valid
    } else if (matched == 1) {
        // only nam was assigned
    } else {   // Includes EOF case
        // Nothing was assigned
        break;
    }
}

关于c - 读取不一致的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21229895/

相关文章:

c - 如何理解递增无符号值概念?

c - 如何减少c程序中全局变量带来的依赖

c - 在拇指驱动器上使用 open()

git - 如何在 Git 存储库中查找和恢复已删除的文件?

c - 解析带有空格的逗号分隔字符串

c++ - 使用 sscanf 的堆栈损坏

c - 管道和 fork ,不显示在标准输出上

c - 如何从Windows内核空间中的任意地址获取模块镜像名称?

java - 创建 Vector<Vector<String>> 以将 .txt 文件导入 JTable

c++ - 使用 scanf 读取 long int