在 C++ 中以字节块为单位读取和写入文件
read and write file in chunks of bytes in c++
我已经到处搜索过它,但我似乎无法理解如何使用ios::cur。我需要以 10 个字节的块读取整个文件,将这些字节写入缓冲区,然后将该缓冲区写入另一个文件。为此,我发送前 10 个字节,然后发送接下来的 10 个字节,依此类推。但是如何确保指针从上次迭代的位置开始呢?
char* data = 0;
int i = 0;
std::ifstream is("test.txt", std::ifstream::binary);
if (is)
{
is.seekg(0, is.end);
int size = is.tellg();
cout << size << endl;
ofstream obj;
obj.open("new.txt");
while (!is.eof())
{
for (; i <= size;)
{
is.seekg(i, is.beg);
int sz = is.tellg();
// cout<<sz<<endl;
data = new char[sz + 1]; // for the ' '
is.read(data, sz);
data[sz] = ' '; // set ' '
cout << " data size: " << strlen(data) << "n";
cout << data;
i = i + 10;
}
obj.close();
}
}
您不需要重新定位文件位置。
文件位置在每次读取操作后都会更新。
应使用两个文件对象,一个用于输入,另一个用于输出。
在这两种情况下,文件位置都会在每次读取和写入操作后更新。
编辑 1:简化示例
#define BUFFER_SIZE 16
unsigned char buffer[BUFFER_SIZE];
//...
while (input_file.read((char *)buffer, BUFFER_SIZE))
{
output_file.write((char *)buffer, BUFFER_SIZE);
}
如果input_file的位置为偏移量 0,则在第一次读取后,文件位置将为 16。 这可以通过以下方式验证:
int read_file_position = input_file.tellg();
cout << "input file position: " << read_file_position << endl;
while (input_file.read((char *)buffer, BUFFER_SIZE))
{
read_file_position = input_file.tellg();
cout << "input file position: " << read_file_position << endl;
output_file.write((char *)buffer, BUFFER_SIZE);
}
我认为可以简化为:
char* data = 0;
int i = 0;
int size = 0;
int sz = 10;
std::ifstream is("test.txt", std::ifstream::binary);
std::ofstream obj;
data = new char[sz+1];
int read_sz = 0;
if (is)
{
obj.open("new.txt");
read_sz = is.tellg(); //we are at the beginning of the file now
while (!is.eof())
{
int old_read_sz = read_sz; // old position - before next read
is.read(data, sz);
read_sz = is.tellg(); // new position, we've read read_sz-old_read_sz bytes
data[read_sz-old_read_sz] = ' '; // set ' '
// I hope you wanted the two lines below only for debugging purposes :)
cout << " data size so far: " << read_sz << "n";
cout << data << endl;
obj.write(data, read_sz-old_read_sz);
}
obj.close();
is.close();
cout << "total data size: "<< read_sz << endl;
}
读取数据块后,文件光标已经移过该块,因此您无需自己重新定位它(并且从当前位置移动到末尾/开始和返回可能会很昂贵 - 时间上 - 特别是如果你有一个大的输入文件)。
顺便说一下,这里有一个关于该主题的教程:http://www.cplusplus.com/doc/tutorial/files/
更新:忘记了是.read() != 旧的 C 样式读取 :-}
相关文章:
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 读取文件的最后一行并输入到链接列表时出错
- 为什么在读取文件大小时文件IO速度会发生变化
- 读取文件时运行时的未知行为
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C++ 读取文件读取文件不正确
- 读取文件并将其存储在unordered_map中时出现问题
- 读取文件时无法使用 OpenMP 获得加速
- 使用istringstearm和get行缓慢读取文件
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 读取文件时引发异常
- 从标准输入读取文件后读取用户输入
- 在读取文件后重置句柄
- 如何在C++编译时读取文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 读取文件在第二次调用时返回INVALID_HANDLE
- 通过指针读取文件
- 逐行读取文件,并将数据插入变量和数组中