Use fscanf to read from given line

后端 未结 3 578
萌比男神i
萌比男神i 2021-01-22 14:40

I want read a txt file that has up to 10 lines. The file is formatted like this on all lines:

1 1 8
2 2 3
3 1 15
4 2 7

I\'m trying to write a f

3条回答
  •  抹茶落季
    2021-01-22 15:31

    You will have to read all the lines up to the one you want.

    I'd probably use fgets() to read the lines and sscanf() to parse the required line. However, you can add a loop to read the unwanted lines (still fgets()) and then read the line you want with fscanf(). Do check that you got three values: you must check the return value from fscanf(). Also remember to close the file you opened.

    void process(int lineNum, char *fullName)
    {
        FILE *f = fopen(fullName, "r");
    
        if (f == NULL) 
        {
            fprintf(stderr, "Error: could not open %S", fullName);
            return;
        }
    
        int num1, num2, num3;
        for (int i = 0; i < lineNum; i++)
        {
            if (fscanf(f, "%d %d %d", &num1, &num2, &num3) != 3)
            {
                fprintf(stderr, "Format error on line %d\n", i+1);
                fclose(f);
                return;
            }
        }
    
        printf("Numbers are: %d %d %d \n",num1, num2, num3);
        fclose(f);
    }
    

    Note that this code does not actually enforce lines separating the sets of numbers (one of the disadvantages of the file-based members of the scanf() family of functions. For that, you need fgets() and sscanf():

    void process(int lineNum, char *fullName)
    {
        FILE *f = fopen(fullName, "r");
    
        if (f == NULL) 
        {
            fprintf(stderr, "Error: could not open %S", fullName);
            return;
        }
    
        char line[4096];
        for (i = 0; i < lineNum; i++)
        {
            if (fgets(line, sizeof(line), f) == 0)
            {
                fprintf(stderr, "Premature EOF at line %d\n", i+1);
                fclose(f);
                return;
            }
            // Optionally check format here...
        }
    
        int num1, num2, num3;
        if (sscanf(line, "%d %d %d", &num1, &num2, &num3) != 3)
        {
            fprintf(stderr, "Format error on line %d\n", i+1);
            fclose(f);
            return;
        }
    
        printf("Numbers are: %d %d %d \n",num1, num2, num3);
        fclose(f);
    }
    

提交回复
热议问题