二进制文件的I/O

二进制文件的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;
}

在平时使用中要注意,二进制可以处理文件文件,但是文本不能处理二进制文件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值