如何从头到中间读取文件
How to read a file from the begining to the middle
所以我从头到尾读了几行。还行。但现在我的目的是从头到中阅读。我的文件包含浮点数,如下所示。我想如果我计算文件的长度,我会把它放在一个循环中,然后读成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"
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 2D数组来自文本输入,中间有空格
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 为什么在读取文件大小时文件IO速度会发生变化
- 正在读取二进制文件(is_open)
- 如何在标准c ++中流式传输/读取二进制文件的中间部分并写入另一个文件?
- 如何从头到中间读取文件
- 读取中间名为可选文件
- C++以二进制流的形式读取文件,在中间随机跳过字节
- 从文件中读取整数,中间有一个字符串
- 如何从文本文件的中间读取