[英]Read and write bytes from a file (c++)
我想我可能不得不使用一個fstream對象,但我不知道如何。 基本上我想將文件讀入字節緩沖區,修改它,然后將這些字節重寫為文件。 所以我只需要知道如何進行字節i / o。
#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();
從記憶中我認為這是怎么回事。
如果您處理的文件很小,我建議您閱讀整個文件更容易。 然后使用緩沖區並再次寫出整個塊。 這些將向您展示如何讀取塊 - 假設您從上面的回復中填寫打開的輸入/輸出文件
// 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
..........
在執行文件I / O時,您必須在循環中讀取文件,檢查文件結尾和錯誤情況。 您可以像這樣使用上面的代碼
while (fileBufferHere.good()) {
filebufferHere.getline(m_content, 1024)
/* Do your work */
}
#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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.