尝试用C语言逐行读取txt文件

问题描述 投票:0回答:1

基本上我的输入文件的格式为:

I 15 3 15 10 10 20  
S -5 3 15 82  
I -20 80 -4 10  
S 4 -20 8

一行中的整数数量可以变化,但每行的开头始终有一个字符

根据字符值“I”或“S”,我在相应行中插入或搜索给定的整数。由于没有类似于 EOF 的 EOL 条件,我将如何在行尾停止?理想情况下我想使用 fscanf。

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

void readFileLines(char** argv)
{
    FILE* fp = fopen(argv[1], "r");
    char read;
    while(fscanf(fp, "%c\t", &read) != EOF)
    {
        //scan first letter in line until EOF
        if(read == 'I')
        {
            //loop through all values in Line
            int data;
            printf("Inputting...");
            while(fscanf(fp, "%i\t", &data) != EOL) //ERROR (EOL DOESNT WORK)
            {
                //iterate rest of line values til end of line
                printf("%d\t", data);
                
            }
        }
        else if(read == 'S')
        {
            int data;
            printf("Searching...");
            while(fscanf(fp, "%d\t", &data) != EOL) // ERROR (EOL DOESNT WORK)
            {
                printf("%d\t", data);
          
            }
        }

        printf("\n");
        //iterate through to next line in order to scan different letteer
    }
   }

int main(int argc, char** argv)
{
    
     readFileLines(argv);

    return EXIT_SUCCESS;
}

我听说 fgets 在这种情况下可以通过利用 在每行的末尾作为指示行何时结束的方式,但我不太确定该方法是如何工作的。请告诉我!

c file io scanf txt
1个回答
0
投票

正如您在问题中建议的那样,使用

fgets
读取整行,然后 使用
sscanf
从该行中提取数据。您可以循环执行此操作。

#define LINE_LEN 1024

int main() {
    char line[LINE_LEN];
    
    while (fgets(line, LINE_LEN, stdin)) {
        char start;

        if (sscanf(line, "%c", &start) != 1 || !(start == 'I' || start == 'S')) {
            fprintf(stderr, "Format error.\n");
            return 1;
        }

        int num;

        while (sscanf(line, "%d", &num) == 1) {
            // work with each int
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.