我正在尝试读取二进制文件并将其存储在缓冲区中。问题是,二进制文件中有多个以 null 结尾的字符,但它们不在末尾,而是在其他二进制文本之前,所以如果我将文本存储在 '\0' 之后,它只会将其删除缓冲区。
例子:
char * a = "this is a\0 test";
cout << a;
这只会输出:this is 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;
}
最佳答案
我只想提一下,有一种标准方法可以将二进制文件读入缓冲区。
使用 <cstdio>
:
char buffer[BUFFERSIZE];
FILE * filp = fopen("filename.bin", "rb");
int bytes_read = fread(buffer, sizeof(char), BUFFERSIZE, filp);
使用 <fstream>
:
std::ifstream fin("filename.bin", ios::in | ios::binary );
fin.read(buffer, BUFFERSIZE);
当然,您之后如何处理缓冲区完全取决于您。
编辑:使用 <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++:将读取的二进制文件存储到缓冲区中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24716250/