我有一個文件,它的行是那種形式。逐行閱讀C和標識元素
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
你可以添加args.txt文件的副本?或者它的一個pastebin鏈接? – Dancrumb
空行是輸入文件的一部分嗎? – wildplasser