2016-12-17 46 views
0

我正在嘗試讀取 - 寫入一個txt文件,該文件在不同的行中包含多個信息。 它是形式:讀寫C文件中的文本文件

Number-LicencePlate NumberOfSeats 

Name number phonenumber 

Name number phonenumber 

Name number phonenumber 

要閱讀的第一行是很容易使用的fscanf 但是,如何才能使用的fscanf獲得3個不同的變量,我讀它的其餘部分(姓名,號碼,電話) ?

寫入該文件在相同的形式是在一個稍後的階段,但會盡力去解決它..

FILE *bus; 
bus = fopen ("bus.txt","r"); 
if (bus == NULL) 
{ 
    printf("Error Opening File, check if file bus.txt is present"); 
    exit(1); 
} 
fscanf(bus,"%s %d",platenr, &numberofseats); 
printf("Bus Licence plate Nr is: %s and number of seats is: %d", platenr, numberofseats); 
+2

噸:https://www.google.com/search?q=how+to+read+text+file+using+fscanf+site%3Astackoverflow.com – alk

+0

使用while循環! –

+0

可能重複[在C中,我應該如何讀取文本文件並打印所有字符串](http://stackoverflow.com/questions/3463426/in-c-how-should-i-read-a-text-file - 和 - 打印所有字符串) –

回答

0

您應該使用一個循環,以達到你所尋找的是你的代碼除了第一行外沒有讀取任何內容,因爲"FILE *bus;"是指向文本文件第一行的指針。

爲了閱讀它,您可以通過檢查文件結尾(EOF)來使用簡單的while循環。有兩種方法我知道,他們在這裏;

while(!feof(bus)){ 
     fscanf(bus,"%s %d",platenr, &numberofseats); 
     printf("Bus Licence plate Nr is: %s and number of seats is: %d", platenr, numberofseats); 
    } 

該代碼塊在讀取它後會打印每一行。 我們使用過「feof(FILE * stream)」;功能Learn More Here。還有其他文章上建議的替代方法How to read a whole text file

但我會把它放在這裏的解決方案。在這裏重複的

while(fscanf(bus,"%s %d",platenr, &numberofseats)!=EOF){ 
     printf("Bus Licence plate Nr is: %s and number of seats is: %d", platenr, numberofseats); 
    }