如何从头到中间读取文件

How to read a file from the begining to the middle

本文关键字:中间 读取 文件      更新时间:2023-10-16

所以我从头到尾读了几行。还行。但现在我的目的是从头到中阅读。我的文件包含浮点数,如下所示。我想如果我计算文件的长度,我会把它放在一个循环中,然后读成filelenghth/2。但我不能,因为每一行都是 6 位的输入空间和数字可以 change.it 现在不是一个好的编程实践根据数据计算。

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;
            }
        }
    }       
}

您可以执行以下操作:

#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...DesktopMyTextFile.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 onernline twornline threern"

并使用以下偶数换行文本文件:

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

将改为:

"line onernline twornline threern"