二进制文件的I/O使用的是fread, fwrite函数。
先来看函数参数:
size_t fread(
void *buffer, //Storage location for data.
size_t size, //Item size in bytes.
size_t count, //Maximum number of items to be read.
FILE *stream //Pointer to FILE structure.
);
size_t fwrite(
const void *buffer, //Pointer to data to be written.
size_t size, //Item size in bytes.
size_t count, //Maximum number of items to be written.
FILE *stream //Pointer to FILE structure.
);
举个例子:
写入一个二进制文件:
#include <stdio.h>
#include<Windows.h>
#include <stdlib.h>
#pragma warning(disable:4996)
int main()
{
FILE *pFile;
char buffer[] = { 'x','y','z' };
pFile = fopen("myfile.bin", "wb");
fwrite(buffer, sizeof(char), sizeof(buffer), pFile);
fclose(pFile);
system("pause");
return 0;
}
执行程序,project文件夹中会生成一个myfile.bin文件,用Binary Viever 查看内容为:,buffer中的内容生成的二进制文件中被保存为”01111000 01111001 01111010.
接下来对myfile.bin进行fread操作:
int main()
{
FILE * pFile;
long lSize;
char * buffer;
size_t result;
pFile = fopen("myfile.bin", "rb"); //"rb":读取二进制文件
if (pFile == NULL) {
fputs("File error", stderr);
Sleep(500); //使用Sleep可以监测哪一步出现错误导致程序退出
exit(1);
}
fseek(pFile, 0, SEEK_END); //fseek:将文件的位置指针放在序列最后
lSize = ftell(pFile); //ftell:获得文件长度
rewind(pFile); //rewind函数使得光标复位,即回到文件开始处位置
buffer = (char*)malloc(sizeof(char)*lSize); //开辟一段内存,大小为buffer的大小
if (buffer == NULL) {
fputs("Memory error", stderr);
Sleep(500);
exit(2);
}
result = fread(buffer, 1, lSize, pFile); //将buffer内容读入到pFile中
if (result != lSize) {
fputs("reading error", stderr);
Sleep(500);
exit(3);
}
fclose(pFile);
free(buffer); //释放或回收内存
system("pause");
return 0;
}
在平时使用中要注意,二进制可以处理文件文件,但是文本不能处理二进制文件。