1
votes

Writing a program that reads information from a text file and writes it into a binary file. The text file contains:
A first name, last name, an ID number, and a GPA.
The first and last name are char arrays with max length of 255, the ID is an unsigned int, and the GPA is a float. After each line, there is another line with the same 4 pieces of information. How can I loop through to the end of the text file and continue to copy the information into the bin file? For example, say there were 4 or 5 lines each with different students with new ID numbers and GPAs, how can I continue copying them from the text to the binary files? I think I've got the segment inside of the loop, but I am unsure how to implement the loop. I have to use fscanf for the text file and fwrite for the binary. Any help appreciated.

    unsigned char firstName[255];
unsigned char lastName[255];
unsigned int id;
float gpa;

fscanf(textfile, "%s %s %d %f", firstName, lastName, &id, &gpa); //read one line of the text file
printf("%s %s %d %.1f", firstName, lastName, id, gpa); //print line information ((test))

printf("\n");  //newline

//Writing information to binary file

fwrite(firstName, strlen(firstName), 1, binfile);
fwrite(lastName, strlen(lastName), 1, binfile);
fwrite(&id, sizeof(int), 1, binfile);
fwrite(&gpa, 4, 1, binfile);
1

1 Answers

1
votes

fscanf - "On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure. In the case of an input failure before any data could be successfully read, EOF is returned."

So,you can check to see if it is == EOF in while loop

 while(fscanf(textfile, "%s %s %d %f", firstName, lastName, &id, &gpa) != EOF) {
  //Body
 }

Alternatively you can also use feof(stdin)

 while(1){ 
       fscanf(textfile, "%s %s %d %f", firstName, lastName, &id, &gpa); 
       if (feof(textfile)) 
               break; 
       //Body
 }

(PS: If you don't want to let the file read <4 number of entries and stop right there, you can do so by replacing EOF with 4 as fscanf returns count as well)