参考:1.windows c/c++文件读写
2.linux c/c++文件读写
枚举类型定义
c/c++用法:
或
c#用法:
c#:byte[] test=new byte[]{0x01,0x02,0x03};
c/c++:
typedef unsigned char byte;
byte test[3]={0x01,0x02,0x03};
需求:用fread()方法读取二进制文件
代码:
打开文件
bool cbinaryfile::open(const char* filename, fileopenmode openmode)
{
mode = openmode;
char* opm;
switch (openmode)
{
case readonly:opm = "r";
break;
case readandwrite:opm = "r+";
break;
case writeonly:opm = "w";
break;
}
file = fopen(filename, opm);
if (file == NULL)return false;
else return true;
}
读取文件内容
bool cbinaryfile::read(BYTE* buffer, int length)
{
if (file == NULL)return false;
size_t result = fread(buffer, sizeof(BYTE), length, file);
if (result < length)return false;
return true;
}
获取当前文件读取的位置
long cbinaryfile::getcurrentpos()
{
if (file == NULL)return 0;
return ftell(file);
}
方法调用
bool ydsqfilelibgcd::readhead()
{
BYTE buf[8];
if (!file.read(buf, 8)) return false;
packstartpos = file.getcurrentpos();
BYTE buf_time[8];
if (!file.read(buf_time, 8)) return false;
packstartpos = file.getcurrentpos();
BYTE buf_count[216];
if (!file.read(buf_count, 216))return false;
packstartpos = file.getcurrentpos();
return true;
}
输出结果:
错误原因:fopen()的打开方式用了“r”,实际上如果要以二进制读取文件的话需要用“rb” 。
解决方法:fopen()函数改为
bool cbinaryfile::open(const char* filename, fileopenmode openmode)
{
mode = openmode;
char* opm;
switch (openmode)
{
case readonly:opm = "rb";
break;
case readandwrite:opm = "rb+";
break;
case writeonly:opm = "wb";
break;
}
file = fopen(filename, opm);
if (file == NULL)return false;
else return true;
}
改完以后输出结果:
扩展关于fopen()函数相关的内容:(以下图片来自:C 库函数 – fread() | 菜鸟教程 (runoob.com)C 文件读写 | 菜鸟教程 (runoob.com))