【问题标题】:Text file read lost formatting vs slowdown文本文件读取丢失格式与减速
【发布时间】:2017-03-16 17:34:10
【问题描述】:

我一直在努力解决这个问题。

读取文本文件。

使用此代码,格式被替换为 getline...但是加载文件的时间太长了...

    std::string line = "";
    std::string file = "";
    std::ifstream filepath(path);

    if (filepath.is_open())
    {
        while (std::getline (filepath,line) )
        {                   
        file = file + line  + "\r\n";
        }

        filepath.close();
    }

使用此代码加载文件的时间快了大约 10 倍,但格式丢失:

        std::ifstream in(path);
        std::stringstream stream;

        stream << in.rdbuf();

        std::string file(stream.str());

是否可以通过第一种方法的格式获得第二种方法的速度...?还是更好更快的速度且格式不变?

我曾考虑尝试不要在循环中的每个 getline 的第一个示例中继续加载相同的字符串,但早期尝试似乎没有帮助。

【问题讨论】:

  • 当您使用 C++ builder 时,您可以使用 FileOpen/Seek/FileRead/FileWrite/FileClose 您可以将整个文本文件加载到内存中而无需任何更改...... fstreams 很慢并且还在处理控制代码(这就是为什么内容已更改)。如果您想快速访问文本文件,您还可以使用Memo1-&gt;Lines-&gt;LoadFromFile("file.txt"),其中 Memo1 是 VCL TMemo 对象(您需要将其添加到您的表单中)。它不需要可见。

标签: file text stream formatting


【解决方案1】:

好的,再次检查后,不知道这叫什么,但这个字符串优化处理了延迟和格式......哇!

如果有人知道如何让它更快,我很想学习如何......

    std::string line = "";
    std::string file = "";
    std::string tmp_str = "";
    std::ifstream filepath(path);
    unsigned int c = 0;

    if (filepath.is_open())
    {
        while (std::getline (filepath,line) )
        {
            tmp_str = tmp_str + line + "\r\n";
            c++;
            if (c > 100)
            {
                file = file + tmp_str;
                tmp_str = "";
                c = 0;
            }
        }

        if (c != 0) 
        {
            file = file + tmp_str;
        }

        filepath.close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-25
    • 2016-07-20
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多