[英]Read - Write Txt File in C
我正在嘗試閱讀-寫一個txt文件,該文件在不同的行中包含多個信息。 它的形式為:
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);
您應該使用循環來實現所需的功能,因為代碼除了第一行"FILE *bus;"
以外沒有讀取任何內容"FILE *bus;"
是指向文本文件第一行的指針。
為了閱讀所有內容,您可以通過檢查文件結尾(EOF)使用簡單的while循環。 我知道2種方法,它們在這里;
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);”。 功能在此處了解更多信息 。 其他文章中還建議了其他方法如何閱讀整個文本文件
但是我也將它放在這里。
while(fscanf(bus,"%s %d",platenr, &numberofseats)!=EOF){
printf("Bus Licence plate Nr is: %s and number of seats is: %d", platenr, numberofseats);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.