fscanf in C not reading full lines?

后端 未结 3 1824
傲寒
傲寒 2021-01-15 13:59

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 Latt         


        
相关标签:
3条回答
  • 2021-01-15 14:04

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

    Use fgets to read a whole line.

    0 讨论(0)
  • 2021-01-15 14:05

    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);
    }
    
    0 讨论(0)
  • 2021-01-15 14:06

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

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

    This will read a full line.

    0 讨论(0)
提交回复
热议问题