Reputation: 39
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
Upvotes: 1
Views: 5334
Reputation: 40145
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);
Upvotes: 1
Reputation: 442
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:
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:
Upvotes: 0
Reputation: 26315
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;
}
Upvotes: 2