2013-03-17 52 views
-1

此代碼只讀取文本文件中的第一行。我怎樣才能讀取同一文本文件中的多行?謝謝。
L-NAME FNAME具有88.0
L-NAME FNAME的GPA具有90.0如何讀取同一文本文件中的多行?

#include <stdio.h> 
#include <stdlib.h> 
struct stud{ 
char fname[21]; 
char lname[21]; 
float gpa; 
} str; 

int getStudData(struct stud *current_ptr); // struct function format 

int main(void){ 
struct stud str; 
getStudData(&str); 

printf("Last Name: %s\n First Name: %s\n GPA: %.2f\n" 
    , str.fname, str.lname, str.gpa); 
return 0; 
} 

int getStudData(struct stud *current_ptr){ 

FILE *studFile; // declaring a pointer file variable 

studFile = fopen("StudData.txt", "r"); // format for fopen; file-variable = fopen(file_name, mode); 

if (studFile == NULL){ 
    printf("Error: Unable to open StudData.txt file\n"); //test for error 
} 
else { 
    fscanf(studFile, "%20s %20s has a GPA of %f\n" 
     , current_ptr->fname, current_ptr->lname, &current_ptr->gpa); 
    // fscanf(file, format, &parameter-1, ...) 

    fclose(studFile); // The function fclose will close the file. 
} 
return 0; 
} 

回答

0

一個GPA要讀取從一個輸入文件多行,它通常共同指定線的端部(EOL)字符。在大多數情況下,這是換行符('\ n'),並從輸入文件讀取設置爲循環。除非需要讀取一行,停止,讀取一行,停止並重復......您可以創建一個循環結構以逐行讀取文件,直到文件結尾(EOF)爲止到達。

下面的代碼只讀取一行,然後關閉文件。

fscanf(studFile, "%20s %20s has a GPA of %f\n" 
     , current_ptr->fname, current_ptr->lname, &current_ptr->gpa); 
    // fscanf(file, format, &parameter-1, ...) 

    fclose(studFile); // The function fclose will close the file 
+0

那麼哪個while循環我應該在此代碼中使用註釋fclose後?謝謝。 – c0ldhand 2013-03-17 19:17:50

+0

我會建議像這裏發佈的解決方案... [C++示例使用](http://stackoverflow.com/questions/21647/reading-from-text-file-until-eof-repeats-last-line) – jarrodparkes 2013-03-17 19:19:05

+0

我很欣賞你的意見。我找到了解決方案。謝謝。 – c0ldhand 2013-03-17 19:48:58