Skip remainder of line with fscanf in C

前端 未结 3 1734
暖寄归人
暖寄归人 2021-01-06 13:31

I\'m reading in a file and after reading in a number, I want to skip to remaining part of that line. An example of a file is this

2 This part should be skipp         


        
相关标签:
3条回答
  • 2021-01-06 14:00

    I wanted to parse the /proc/self/maps file, but only wanted the first 2 columns (start and end of address range). This worked fine with Linux gcc.

    scanf("%llx-%llx %*[^\n]\n", &i, &e);

    The trick was "%*[^\n]\n" which means skip a sequence of anything except the end of line, then skip the end of line.

    0 讨论(0)
  • 2021-01-06 14:19
    #include <stdio.h>
    
    int main(){
        FILE *f = fopen("data.txt", "r");
        int n, stat;
        do{
            if(1==(stat=fscanf(f, "%d", &n))){
                printf("n=%d\n", n);
            }
        }while(EOF!=fscanf(f, "%*[^\n]"));
        fclose(f);
    
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-06 14:20

    I suggest you to use fgets() and then sscanf() to read the number. scanf() function is prone to errors and you can quite easily get the format string wrong which may seem to work for most cases and fail unexpectedly for some cases when you find it doesn't handle some specific input formats.

    A quick search for scanf() problems on SO would show how often people get it wrong and run into problems when using scanf().

    Instead fgets() + sscanf() gives would give you better control and you know for sure you have read one line and you can process the line you read to read integer out it:

    char line[1024];
    
    
    while(fgets(line, sizeof line, fp) ) {
    
       if( sscanf(line, "%d", &num) == 1 ) 
       {
        /* number found at the beginning */
       }
       else
       {
        /* Any message you want to show if number not found and 
         move on the next line */
       }
    }
    

    You may want to change how you read num from line depending on the format of lines in the file. But in your case, it seems the integer is either located at first or not present at all. So the above will work fine.

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