从文件中读取和写入字节 (c++)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2285900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read and write bytes from a file (c++)
提问by jmasterx
I think I probably have to use an fstream object but i'm not sure how. Essentially I want to read in a file into a byte buffer, modify it, then rewrite these bytes to a file. So I just need to know how to do byte i/o.
我想我可能必须使用 fstream 对象,但我不确定如何使用。本质上,我想将文件读入字节缓冲区,对其进行修改,然后将这些字节重写到文件中。所以我只需要知道如何进行字节 i/o。
回答by Craig
#include <fstream>
ifstream fileBuffer("input file path", ios::in|ios::binary);
ofstream outputBuffer("output file path", ios::out|ios::binary);
char input[1024];
char output[1024];
if (fileBuffer.is_open())
{
fileBuffer.seekg(0, ios::beg);
fileBuffer.getline(input, 1024);
}
// Modify output here.
outputBuffer.write(output, sizeof(output));
outputBuffer.close();
fileBuffer.close();
From memory I think this is how it goes.
根据记忆,我认为事情是这样的。
回答by Fadrian Sudaman
If you are dealing with a small file size, I recommend that reading the whole file is easier. Then work with the buffer and write the whole block out again. These show you how to read the block - assuming you fill in the open input/output file from above reply
如果您正在处理小文件,我建议阅读整个文件更容易。然后使用缓冲区并再次写出整个块。这些向您展示了如何读取块 - 假设您填写了上述回复中打开的输入/输出文件
// open the file stream
.....
// use seek to find the length, the you can create a buffer of that size
input.seekg (0, ios::end);
int length = input.tellg();
input.seekg (0, ios::beg);
buffer = new char [length];
input.read (buffer,length);
// do something with the buffer here
............
// write it back out, assuming you now have allocated a new buffer
output.write(newBuffer, sizeof(newBuffer));
delete buffer;
delete newBuffer;
// close the file
..........
回答by HelloWorld
#include <iostream>
#include <fstream>
const static int BUF_SIZE = 4096;
using std::ios_base;
int main(int argc, char** argv) {
std::ifstream in(argv[1],
ios_base::in | ios_base::binary); // Use binary mode so we can
std::ofstream out(argv[2], // handle all kinds of file
ios_base::out | ios_base::binary); // content.
// Make sure the streams opened okay...
char buf[BUF_SIZE];
do {
in.read(&buf[0], BUF_SIZE); // Read at most n bytes into
out.write(&buf[0], in.gcount()); // buf, then write the buf to
} while (in.gcount() > 0); // the output.
// Check streams for problems...
in.close();
out.close();
}
回答by Tanuj
While doing file I/O, you will have to read the file in a loop checking for end of file and error conditions. You can use the above code like this
在执行文件 I/O 时,您必须在检查文件结尾和错误条件的循环中读取文件。你可以像这样使用上面的代码
while (fileBufferHere.good()) {
filebufferHere.getline(m_content, 1024)
/* Do your work */
}