无法使用 fscanf() 读取一行 [英] Trouble reading a line using fscanf()

查看:39
本文介绍了无法使用 fscanf() 读取一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码读取一行:

I'm trying to read a line using the following code:

while(fscanf(f, "%[^

]s", cLine) != EOF )
{
    /* do something with cLine */
}

但不知何故,我每次都只得到第一行.这是阅读一行的糟糕方式吗?我应该修复什么才能使其按预期工作?

But somehow I get only the first line every time. Is this a bad way to read a line? What should I fix to make it work as expected?

推荐答案

使用 fscanf() 函数几乎总是一个坏主意,因为它可以离开您的文件失败时指针位于未知位置.

It's almost always a bad idea to use the fscanf() function as it can leave your file pointer in an unknown location on failure.

我更喜欢使用 fgets() 来获取每一行,然后使用 sscanf() .然后,您可以继续检查您认为合适的读入行.类似的东西:

I prefer to use fgets() to get each line in and then sscanf() that. You can then continue to examine the line read in as you see fit. Something like:

#define LINESZ 1024
char buff[LINESZ];
FILE *fin = fopen ("infile.txt", "r");
if (fin != NULL) {
    while (fgets (buff, LINESZ, fin)) {
        /* Process buff here. */
    }
    fclose (fin);
}

fgets() 似乎是您要执行的操作,读取字符串直到遇到换行符.

fgets() appears to be what you're trying to do, reading in a string until you encounter a newline character.

这篇关于无法使用 fscanf() 读取一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆