简体   繁体   中英

Read - Write Txt File in C

I am trying to read - write a txt file that has several info in different lines. It is in the form of:

Number-LicencePlate NumberOfSeats

Name  number  phonenumber

Name  number  phonenumber

Name  number  phonenumber

To read the first line it is pretty easy using fscanf But how can I read the rest of it using fscanf to obtain 3 different variables (Name,Number,phone)?

Write to this file in the same form comes at a later stage but will try to work it out..

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);

You should use a loop in order to achieve what you are looking for as your code is not reading anything except the first line as "FILE *bus;" is a pointer to the first line of the text file.

In order to read it all you can use a simple while loop by checking End of File(EOF). There are 2 methods that I am aware of and here they are;

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

This code block will print each line after reading it. We have used "feof ( FILE * stream );" function Learn More Here . There are also alternative ways suggested on other articles How to read a whole text file

But I will put it here that solution as well.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM