2012-05-23 79 views
0

我有一個文件,它的行是那種形式。逐行閱讀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 
+0

你可以添加args.txt文件的副本?或者它的一個pastebin鏈接? – Dancrumb

+0

空行是輸入文件的一部分嗎? – wildplasser

回答

1

通過

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

更新替換

assignments = fscanf(file1, "%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 

這是預期的,應該有一個繼續(或等同物)在糟糕塊。

我加了繼續說明。

輸出,用於同該方案繼續:

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 
1

您正在閱讀的線用於fgets文本,然後將其丟棄(因爲你的fscanf再次讀取)的

例子。

而不是調用fgets作爲您的while循環守衛,請考慮使用函數feof。因此,環路防護將成爲

while(!feof(file1)) 
+0

錯誤。原文是正確的。 (除了第二個fscanf()) – wildplasser