简体   繁体   中英

Reading multiple lines at a time in text file - C

I have an input file basically like this:

Group 1

Gabe Theodore Simon

Score 10

Group 2

Josh James Matthew

Score 9

I usually use fscanf in reading files but I do not know how to use it in reading three lines at a time. I am still new to c so can someone please help me?

EDIT: Sorry I forgot to say that the group members isn't always 3. It can even be hundreds

You can read line by line from the file using fgets .

Something like this will get you started:

#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 100

int
main(void) {
    FILE *fp;
    char line[MAXSIZE];

    fp = fopen("yourfile.txt", "r");
    if (fp == NULL) {
        fprintf(stderr, "%s\n", "Error reading from file");
        exit(EXIT_FAILURE);
    }

    while (fgets(line, MAXSIZE, fp) != NULL) {
        printf("%s\n", line);
    }

    fclose(fp);

    return 0;
}

Here, I refactored everything I had previously thought about. I am providing a fresh solution to get lines in a text file using C tools. I was able to achieved such by combining different programming techniques such as the following:

  • Regex
  • C provided functions:

    scanf() : collects the string
    getchar() : checks for the end of the file

     #include <stdio.h> #include <stdlib.h> #define MAXSIZE 500 int main(void) { char line[MAXSIZE]; while (scanf("%499[^\\n]", line)== 1 && getchar() != EOF) { printf("%s\\n", line); } return 0; } 

Steps to run this C code from terminal:

  1. Create a text file
  2. Compile the C code
  3. Run it by redirecting text file : ./(executable_goes_here) < (text_file_created_goes_here)

like this:

char group[32], name[128], score[32];
FILE *fp = fopen("score.txt", "r");
while(3 == fscanf(fp, "%31[^\n]%*c%127[^\n]%*c%31[^\n]%*c", group, name, score)){
    printf("%s, %s, %s\n", group, name, score);
}
fclose(fp);

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