fscanf in C not reading full lines?

牧云@^-^@ 提交于 2019-12-19 10:07:41

问题


This is so stupidly simple but I'm just having issues with it.

A text file has a header,

e.g.,

# Avizo BINARY-LITTLE-ENDIAN 2.1

define Lattice 496 384 470

Parameters {
    AlignTransform {
        slice0000 0 -0 -30 -1,
        slice0001 0 -0 -30 -1,
        slice0002 0 -0 -30 -1,

And I'm trying to read each of these lines using fscanf.

   int i;
   for (  i = 0; i < 10; i++ ) {
     fscanf(fp, "%s\n", buf);  
     printf("%d) %s\n",i,buf);
   }

resulting in this

0) #
1) Avizo
2) BINARY-LITTLE-ENDIAN
3) 2.1
4) define
5) Lattice
6) 496
7) 384
8) 470
9) Parameters

So it's parsing the whitespace instead of newlines. Not sure what's happening.


回答1:


The %s specifier in fscanf reads words, so it stops when reaching a space.

Use fgets to read a whole line.




回答2:


I recommend that you use fgets, but if you insist on using fscanf:

fscanf(fd, "%[^\n]\n", buff);

This will read a full line.




回答3:


Although %s may mean "string", but fscanf (as scanf) is not a greedy mathing one, you should tell it the seperator is "new line". And, You'd better to set maxinum buffer size to prevent buffer overflow.

#include <stdio.h>

#define NAME_MAX    80
#define NAME_MAX_S "80"

int main(void)
{
    static char name[NAME_MAX + 1]; // + 1 because of null
    if(scanf("%" NAME_MAX_S "[^\n]", name) != 1)
    {
        fputs("io error or premature end of line\n", stderr);
        return 1;
    }

    printf("Hello %s. Nice to meet you.\n", name);
}


来源:https://stackoverflow.com/questions/10477551/fscanf-in-c-not-reading-full-lines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!