C ++:将读取的二进制文件存储到缓冲区中 [英] C++: Store read binary file into buffer
问题描述
我试图读取二进制文件并将其存储在缓冲区中。问题是,在二进制文件中有多个以null结尾的字符,但它们不在结尾,而是在其他二进制文本之前,所以如果我将文本存储在'\0'后,它只是删除它
I'am trying to read a binary file and store it in a buffer. The problem is, that in the binary file are multiple null-terminated characters, but they are not at the end, instead they are before other binary text, so if I store the text after the '\0' it just deletes it in the buffer.
示例:
char * a = "this is a\0 test";
cout << a;
这将只输出:这是一个
这里是我真正的代码:
此函数读取一个字符
bool CStream::Read (int * _OutChar)
{
if (!bInitialized)
return false;
int iReturn = 0;
*_OutChar = fgetc (pFile);
if (*_OutChar == EOF)
return false;
return true;
}
这是我如何使用它:
char * SendData = new char[4096 + 1];
for (i = 0; i < 4096; i++)
{
if (Stream.Read (&iChar))
SendData[i] = iChar;
else
break;
}
推荐答案
有一个标准的方式从二进制文件读取到缓冲区。
I just want to mention that there is a standard way to read from a binary file into a buffer.
使用< cstdio>
:
char buffer[BUFFERSIZE];
FILE * filp = fopen("filename.bin", "rb");
int bytes_read = fread(buffer, sizeof(char), BUFFERSIZE, filp);
使用< fstream>
:
Using <fstream>
:
std::ifstream fin("filename.bin", ios::in | ios::binary );
fin.read(buffer, BUFFERSIZE);
之后用缓冲区做的事情当然取决于你。
What you do with the buffer afterwards is all up to you of course.
编辑:使用< cstdio>
$ b
Full example using <cstdio>
#include <cstdio>
const int BUFFERSIZE = 4096;
int main() {
const char * fname = "filename.bin";
FILE* filp = fopen(fname, "rb" );
if (!filp) { printf("Error: could not open file %s\n", fname); return -1; }
char * buffer = new char[BUFFERSIZE];
while ( (int bytes = fread(buffer, sizeof(char), BUFFERSIZE, filp)) > 0 ) {
// Do something with the bytes, first elements of buffer.
// For example, reversing the data and forget about it afterwards!
for (char *beg = buffer, *end=buffer + bytes; beg < end; beg++, end-- ) {
swap(*beg, *end);
}
}
// Done and close.
fclose(filp);
return 0;
}
这篇关于C ++:将读取的二进制文件存储到缓冲区中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!