如何从头到尾读取文件

时间:2015-04-19 06:23:35

标签: c++

所以我从头到尾读了一行。没关系。但现在我的目的是从头到尾阅读。我的文件包含浮点数,如下所示。我想如果我计算文件的长度,我会把它放在循环中并将其读作filelenghth/2。 但我不能,因为每行都是6位的输入空格,数字可以改变。现在不是根据数据计算好的编程习惯。

1.33
5.45
6.21
2.48
3.84
7.96
8.14
4.36
2.24
9.45

我需要比以下代码更有效的解决方案。你为此目的建议了什么样的解决方案。

fstream inputNumbersFile("input.txt");
ifstream lengthOfNumbersFile("input.txt"); // for getting size of file
lengthOfNumbersFile.seekg(0, lengthOfNumbersFile.end);
int lengthFile = lengthOfNumbersFile.tellg();;
if (inputNumbersFile.is_open())
{
    for (int i = 0; i < lengthFile;)
    {
        while (getline(inputNumbersFile, line))
        {               
            cout << line << endl;
            i = i + 6;
            if (i == lengthFile/2)
            {
                break;
            }
        }
    }       
}

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

#include <string>
#include <fstream>
#include <stdexcept>
#include <iostream>

using std::string;
using std::ifstream;
using std::ios_base;
using std::ios;
using std::invalid_argument;
using std::getline;
using std::cout;
using std::cerr;
using std::endl;

static string file_str(const string & path)
{
    ifstream ifs(&path[0], ios_base::in | ios_base::binary);
    if (!ifs)
        throw invalid_argument("File: " + path + " not found!");
    // Enable exceptions
    ifs.exceptions();

    // Init string buffer to hold file data.
    string buffer;
    // Set ifs input position indicator to end.
    ifs.seekg(0, ios::end);
    // Set the buffer capacity to exactly half the file contents size.
    buffer.resize(ifs.tellg() / 2);
    // Set ifs input position indicator to beginning.
    ifs.seekg(0);
    string::size_type buffer_size(buffer.size());
    // Read file contents into string buffer.
    ifs.read(&buffer[0], buffer_size);
    if (buffer[buffer_size - 1] != '\n')
    {
        // Continue reading until we find the next newline.
        string remaining;
        getline(ifs, remaining);
        // Append to buffer.
        buffer += remaining + '\n';
    }
    ifs.close();
    // Return by RVO.
    return buffer;
}

int main(int argc, const char * argv[])
{
    try
    {
        string file_contents = file_str(R"(C:\Users\...\Desktop\MyTextFile.txt)");
        cout << file_contents << endl;
    }
    catch (string message)
    {
        cerr << message << endl;
        return 1;
    }
    return 0;
}

其中,使用以下奇数换行文本文件:

line one
line two
line three
line four
line five

请阅读:

"line one\r\nline two\r\nline three\r\n"

使用以下偶数新文本文件:

line one
line two
line three
line four
line five
line six

请阅读:

"line one\r\nline two\r\nline three\r\n"