使用不同的数据类型逐行读取文件中的数据

时间:2013-10-27 12:22:46

标签: c file-io

我有一个.txt文件:

A B C
England vs autralia
2004
100
D E F
japan vs argentina
3045
140
D E F
india vs pakistan
2012
150
J F G
south africa vs india
1967
100
K GHD D
australia vs pakistan
1993
453
Z E Q
pakistan vs england
2013
150  

我想读它并存储在变量中。 (每行转到一个变量)。

我有这段代码,但它一次读取一行并作为字符串。

if ( file != NULL )
{
    i=1;
    char line [ 100 ]; /* line size */
    while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
        {
            fputs ( line, stdout ); /* write the line */
            i++;
        }
    fclose ( file );
}  

实际上我想一次读4行。但似乎不可能。所以我可以将4行放在由空格分隔的单行中,但在这种情况下,扫描多字符串是不可能的。

那么,我该怎么做?

2 个答案:

答案 0 :(得分:3)

使用计数器确定您所在的四行中的哪一行:

#include <stdio.h>
#include <string.h>

void doit( FILE *file)
{
char line [ 100 ]; /* line size */
unsigned iii;
size_t len;

    for(iii=0;  fgets ( line, sizeof line, file); iii++ ) /* read a line */
        {
        len = strlen(line);
        while (len && line[len-1] == '\n') line[--len] = 0;
        switch (iii % 4) {
        case 0: /* handle first line here */
               break;
        case 1: /* handle second line here */
               break;
        case 2: /* handle third line here */
               break;
        case 3: /* handle fourth line here */
               break;
                }
        }
}

答案 1 :(得分:0)

逐行阅读,并且由于格式似乎已修复,因此您始终知道每行上有哪些类型。

所以,例如喜欢这个伪代码

while (continue_reading)
{
    // E.g. "A B C"
    get_line()
    parse_line_into_three_string()

    // E.g. "England vs autralia"
    get_line()
    parse_whole_line_as_a_single_string()

    // E.g. "2004"
    get_line()
    parse_line_as_a_number()

    // E.g. "100"
    get_line()
    parse_line_as_a_number()

    do_something_with_all_data()
}
相关问题