[英]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 得分10
Group 2 2组
Josh James Matthew 乔什·詹姆斯·马修
Score 9 得分9
I usually use fscanf in reading files but I do not know how to use it in reading three lines at a time. 我通常在读取文件时使用fscanf,但我不知道如何在一次读取三行时使用它。 I am still new to c so can someone please help me?
我对c还是陌生的,所以有人可以帮我吗?
EDIT: Sorry I forgot to say that the group members isn't always 3. It can even be hundreds 编辑:对不起,我忘了说小组成员并不总是3人。甚至可以是数百人。
You can read line by line from the file using fgets
. 您可以使用
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.
我正在提供一种新的解决方案,以使用C工具在文本文件中获取行。 I was able to achieved such by combining different programming techniques such as the following:
通过结合以下不同的编程技术,我得以实现:
C provided functions: C提供的功能:
scanf() : collects the string scanf() :收集字符串
getchar() : checks for the end of the file getchar() :检查文件结尾
#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: 从终端运行此C代码的步骤:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.