-1

This code only reads the first line in the text file. How can I read multiple lines in the same text file?. Thank you.
lname fname has a GPA of 88.0
lname fname has a GPA of 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;
}
Mat
  • 202,337
  • 40
  • 393
  • 406
c0ldhand
  • 35
  • 1
  • 7

1 Answers1

0

To read multiple lines from an input file, it usually common to specify an end of line (EOL) character. In most cases, this is the newline character ('\n'), and reading from the input file is setup as a loop. Unless it is necessary to read-a-line, STOP, read-a-line, STOP, and repeat...you can create a loop structure to read the file line-by-line until the end of file (EOF) is reached.

The code below only reads one line and then closes file.

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
jarrodparkes
  • 2,378
  • 2
  • 18
  • 26