我有一个文件,它的行就是这种形式。
39.546147 19.849505 Name Last
而且我不知道我有多少行。我想要的是逐行阅读文本并简单地保留这四个元素中的每一个分隔变量。(在这种情况下,有 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