C - 如何使用fscanf()与可变长度的行?

时间:2016-04-09 09:49:32

标签: c file scanf

我正在阅读包含字符和大量整数的文件。我正在使用fscanf函数读取它以检索所有整数。但是我事先并不知道有多少整数会在一条线上。我怎么还能让它发挥作用?

问题是要使用简单函数fscanf我必须事先知道我的文件将具有什么结构,即有多少整数等...

我想使用类似的东西:

fscanf(fp, "%d//%d %d//%d", &array1[0], &array1[1], &array1[3], &array1[4]);

例如:这是我的文件

f 7//1 8//1 10//1 9//1

f 9//2 10//2 12//2 11//2

f 11//3 12//3 14//3 13//3

f 21//8 22//8 24//8 23//8

f 23//9 24//9 26//9 25//9

f 25//10 26//10 28//10 27//10

f 65//30 66//30 68//30 67//30

f 10//31 8//31 70//31 68//31 66//31 64//31 62//31 60//31 58//31 56//31 54//31 52//31 50//31 48//31 46//31 44//31 42//31 40//31 38//31 36//31 34//31 32//31 30//31 28//31 26//31 24//31 22//31 20//31 18//31 16//31 14//31 12//31

f 67//32 68//32 70//32 69//32

1 个答案:

答案 0 :(得分:1)

您不能使用fscanf按行读取文件。您可以做的是使用fgets阅读行,然后使用strtoksscanf处理这些行。

int read_n, value;
char line[SIZE], *val;
char delims[] = " //\r\n\t ";

while (fgets(line, size, file) != NULL)
{
    val = strtok(line, delims);
    read_n = sscanf(val, "%d", &value);

    while(read_n > 0)
    {
        printf("Read [%d]\n", value);
        val = strtok(NULL, delims);
        read_n = (val == NULL) ? 0 : sscanf(val, "%d",&value);
    }
}

在多线程环境中使用strtok_r