在C中逐行阅读和识别元素

时间:2012-05-23 16:31:13

标签: c file-io

我有一个文件,其行是该格式。

39.546147  19.849505  Name  Last 

我不知道有多少行。我想要的是逐行阅读文本,并简单地将这4个元素中的每一个分开变量。 (在这种情况下,2个浮点数和2个标记-char []。)

到目前为止,我的代码是:

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

int main(int argc, char *argv[])
{
   FILE * file1;

file1 = fopen("args.txt","r");
float var0;
float var1;
char S1 [128];
char S2 [128];
int assignments;

if ( file1 != NULL ){
    char line [ 256 ];
    while ( fgets ( line, sizeof line, file1 ) != NULL ) //read a line
    {
        //printf("%s\n",line);
        assignments = fscanf( file1, "%f %f %s %s",&var0, &var1, &S1, &S2 );
            if( assignments < 4 ){
                fprintf( stderr, "Oops: only %d fields read\n", assignments );
            }
        printf("%f --- %f ---- %s ---- %s  \n",var0, var1,S1,S2);
    }
    fclose ( file1 );

}
else {
    perror ( "args.txt" ); /* why didn't the file open? */
}
return 0;
}

我得到的结果是它只读取一个元素。你可以帮我吗?

args.txt的例子

39.546147  19.849505  george  papad 

39.502277  19.923813  nick  perry 

39.475508  19.934671  john  derrick

2 个答案:

答案 0 :(得分:1)

您正在阅读带有fgets的文本行,然后将其丢弃(因为您再次使用fscanf阅读)。

不要将fgets作为while循环保护调用,而是考虑使用feof函数。因此,环路保护将成为

while(!feof(file1))

答案 1 :(得分:1)

替换

assignments = fscanf( file1, "%f %f %s %s",&var0, &var1, &S1, &S2 );

通过

assignments = sscanf( line, "%f %f %s %s",&var0, &var1, &S1, &S2 );

更新:以下程序适用于此。

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

int main(int argc, char *argv[])
{
FILE * file1;

float var0;
float var1;
char S1 [128];
char S2 [128];
char line [ 256 ];
int assignments;

file1 = fopen("args.txt","r");

if ( file1 == NULL ){
        perror ( "args.txt" ); /* why didn't the file open? */
        return 1;
        }

    while ( fgets ( line, sizeof line, file1 ) != NULL ) //read a line
    {
        //printf("%s\n",line);
        assignments = sscanf( line, "%f %f %s %s",&var0, &var1, S1, S2 );
            if( assignments < 4 ){
                fprintf( stderr, "Oops: only %d fields read\n", assignments );
                continue; /* <<----- */
            }
        printf("%f --- %f ---- %s ---- %s  \n",var0, var1,S1,S2);
    }
    fclose ( file1 );

return 0;
}

OUTPUT(对于带空行的输入文件)

39.546146 --- 19.849504 ---- george ---- papad  
Oops: only -1 fields read
39.546146 --- 19.849504 ---- george ---- papad  
39.502277 --- 19.923813 ---- nick ---- perry  
Oops: only -1 fields read
39.502277 --- 19.923813 ---- nick ---- perry  
39.475510 --- 19.934671 ---- john ---- derrick

这是预期的,oops-block中应该有一个continue(或等效的)。

我添加了继续说明。

带有continue的程序输出:

39.546146 --- 19.849504 ---- george ---- papad  
Oops: only -1 fields read
39.502277 --- 19.923813 ---- nick ---- perry  
Oops: only -1 fields read
39.475510 --- 19.934671 ---- john ---- derrick