如何使用fgets逐行读取文件 [英] How to use fgets to read a file line by line

查看:651
本文介绍了如何使用fgets逐行读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程的新手,所以有一些我不知道的基本知识和常识。我有一个关于如何正确使用fgets的问题。根据对fgets的解释,似乎fgets应该在读取n-1个字符,按EOF或按换行符时停止。
例如,我创建一个文本文件,如下所示:

I'm new at programming so there are some basics and maybe common sense that I don't know. I have a question about how to use fgets right. Based on the explanation of fgets, it seems that fgets should stop whenever it reads n-1 characters, hit the EOF or hit a newline character. For example, I create a text file like below:

red  100
yellow  400
blue  300
green 500
purple 1000
...

颜色和整数之间用制表符分隔。创建此文本文件时,我需要在每行末尾按Enter键以开始新行。在这种情况下,按Enter键等于添加一个换行符 \n,对吗?

The color and the integer is separated by a tab. When I create this text file, I need to hit enter at the end of each line to start a new line. In this case, hitting enter equals to add a newline character, '\n', is that right?

如果每行末尾都有一个 \n是正确的,我将运行fgets代码,如下所示:

If it is right that there is a '\n' at the end of each line, I run the fgets code as below:

fgets(string, 100, fp);

由于每行包含的字符少于100个,因此fgets应该在换行符之前达到最大长度限制,它应该停止并返回NULL。

Since the characters contain in each line is much less than 100, the fgets should hit the newline character before reach the maxlength limit and it should stop and return a NULL. Is that correct?

如果我的理解不正确,则每行末尾都没有'\n',或者fgets不会在末尾停止我应该选择每行的最大长度(即fgets(string,N,stream)函数中的N)的数量是多少,以确保由于我的最终目标是解析每行并存储文件而正确输入文件每行变成一个结构。顺便说一下,文件中有100行。

If my understanding above are not right, there is no '\n' at the end of each line, or fgets does not stop at the end of each line, what is the number of maxlength (i.e., the N in the fgets(string, N, stream) function) should I pick to make sure that the file input properly due to my ultimate goal is to parsing each line and store each line into a structure. By the way, there are 100 lines in the file.

推荐答案

 #include <stdio.h>

 int main()
 {
    char str[150],str2[100][150];
    int i=0,j=0,value[100];
    FILE* fp;
    fp = fopen("file.txt", "r");
    while (fgets(str,150, fp)) {
        i++;
        printf("%3d: %s\n", i, str);
        /** if you want to split value and string*/
        sscanf(str,"%s %d",&str2[j],&value[j]);
        printf("%d %s\n",value[j],str2[j]);
        j++;
    }
    fclose(fp);
    return 0;
}

这篇关于如何使用fgets逐行读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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