逐行读取文本文件 [英] read line by line text file

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

问题描述

嗨 我有一个文本文件.该文件中有3个文本留置权.
我想阅读文本文件.
如何才能逐行读取此文件?

Hy I have a text file . in this file there are 3 text liens .
I want to read the text file .
How can I read line by line this file ?

推荐答案

您可以使用C库 iostream [ ^ ]类.
You could use the C library fread()[^] function, or the C++ iostream[^] class.


如果要使其保持简单愚蠢:
If you want to keep it simple stupid:
#include <stdio.h>

void process_line(const char* line)
{
    // you line processing here
}

void test()
{
    FILE* f = fopen("myfile.txt", "r");
    if (f)
    {
        // replace the line below to "for (;;)" if you want to process all lines
        for (int i=0; i<3; ++i)
        {
            const int MAX_LINE_LENGTH = 0x100;
            char line[MAX_LINE_LENGTH];
            if (!fgets(line, sizeof(line), f))
                break;
            int len = strlen(line);
            if (len>0 && line[len-1]=='\n')
                line[len-1] = 0;
            process_line(line);
        }
        fclose(f);
    }
}


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

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