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

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

问题描述

我想用下面的code读取行:

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

while(fscanf(f, "%[^\n\r]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.

我preFER使用与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天全站免登陆