gpt4 book ai didi

c - 读取不一致的文件

转载 作者:太空宇宙 更新时间:2023-11-04 05:59:41 26 4
gpt4 key购买 nike

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/

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