逐行读取文本文件并在C中检索每行的内容 [英] Read a text file line by line and retrieve the content of each line in C

查看:33
本文介绍了逐行读取文本文件并在C中检索每行的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个文本文件如下:

Say a text file would be like:

1, 2345, 7788, 463, ABC
2, 387, 1100, 321, CCC
2, 2222, 22222, 22, DSA

所以这个文本文件有3行,我的项目需要我们实现一个函数,逐行读取这个文本文件,读取特定行时,获取每一行的内容,然后检查这个文件的内容线.

So there are 3 lines in this text file, and my project needs us to realize a function that read this text file line by line, and retrieve each line's content when a specific line is read, and then examine the content of this line.

例如,我会从第一行开始读取这个文件.所以当第一行被读取时(1, 2345, 7788, 463, ABC),我首先需要将这一行存储到一个字符串中(假设它是 char[] str),然后我需要将这个 str 分成 5 部分, 并且每个片段都包含由逗号分隔的五个不同的文件内容,例如 p1、p2、p3、p4 和 p5.然后我需要检查 p3 是否为1100".如果是,则关闭此文件并继续执行程序,如果不是,则我需要继续阅读第二行并执行相同的操作,显然 1100 是第二行的第三个字段,因此阅读后这一行函数将终止.

For example, I would begin to read this file from the first line. So when this first line is read(1, 2345, 7788, 463, ABC), I will first need to store this line into a string (say it's char[] str), and then I need to break this str into 5 pieces, and each piece contain those five different filed-content separated by the comma, say p1, p2, p3, p4 and p5. Then I need to examine if the p3 is "1100". If it is, then close this file and continue the program, and if it's not, then I would need to continue to read the second line and do the same thing, and apparently 1100 is the third filed of the second line, so after reading this line the function would terminate.

现在有人能告诉我如何实现它吗?我对 C 很陌生,我在互联网上搜索过一些关于 fgets() 的信息,例如:

Now could anybody tell me how could I implement it? I'm very new to C and I've searched the internet and got something about fgets(), like:

if (fgets(str, 60, "text.txt")!=NULL){
    puts(str);
}

但在这里我看不到这个 frets() 逐行读取文本文件的任何提示.

but here I can't see any hint that this frets() reads the text file line by line.

提前致谢!:D

推荐答案

你想要这个:

char str[60];
FILE* f = fopen("text.txt", "r");
if (f == NULL) exit(1);
while(fgets(str, 60, f) != NULL){
    fputs(str, stdout);
}
fclose(f);

这篇关于逐行读取文本文件并在C中检索每行的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆