[英]C++ Opening a binary file
I want to open a binary file in C++. 我想用C ++打开一个二进制文件。 but I have this function in C:
但我在C中有这个功能:
uint openPacket(const char* filename, unsigned char** buffer) {
FILE* fp = fopen(filename, "rb");
if (fp) {
size_t result;
fseek(fp, 0, SEEK_END);
long fsize = ftell(fp);
rewind(fp);
*buffer = new unsigned char[fsize];
result = fread(*buffer, 1, fsize, fp);
if (result != fsize) {
printf("Reading error in %s, unable to send packet!\n", filename);
delete[] * buffer;
fsize = 0;
}
fclose(fp);
return fsize;
} else {
printf("Couldn't open %s for packet reading, unable to send packet!\n", filename);
return 0;
}
}
I want to make something like: string OpenPacket(string filename) but don't work :( 我想做类似的东西:字符串OpenPacket(字符串文件名)但不起作用:(
May be this is a possible wrapper function: 可能这是一个可能的包装函数:
std::string openPacket( const std::string& filename )
{
unsigned char* buff;
uint size = openPacket( filename.c_str(), &buff );
if( size )
{
std::string s( reinterpret_cast<const char*>(buff), size );
delete [] buff;
return s;
}
return std::string();
}
I think You Need this: 我想你需要这个:
uint openPacket(const char* filename, unsigned char** buffer) {
ifstream file (filename, ios::in|ios::binary|ios::ate);
streampos size;
if (file.is_open())
{
size = file.tellg();
*buffer = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout << "the entire file content is in memory";
return size;
}
For reference Check this 供参考检查
hope this will help you. 希望这会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.