二进制文件读取写入(一)

最近在老师推荐下,跟着田纳西大学James S. Plank的课程安排学习Unix Systems Programming

Lab链接在这里:
http://web.eecs.utk.edu/~plank/plank/classes/cs360/360/labs/lab2/index.html

在这里向和我一样没接触太多程序设计同学介绍一下学习过程:

为什么使用二进制IO

引自:Advanced Programming in the UNIX Environment 3rd Edition

5.9 二进制I/O
The functions from Section 5.6 operated with one character at a time, and the functions from Section 5.7 operated with one line at a time. If we’re doing binary I/O, we often would like to read or write an entire structure at a time. To do this using getc or putc, we have to loop through the entire structure, one byte at a time, reading or writing each byte. We can’t use the line-at-a-time functions, since fputs stops writing when it hits a null byte, and there might be null bytes within the structure. Similarly, fgets won’t work correctly on input if any of the data bytes are nulls or newlines. Therefore, the following two functions are provided for binary I/O.

函数原型

#include <stdio.h>
size_t fread(void *restrict ptr, size_t size, size_t nobj, FILE *restrict fp);
size_t fwrite(const void *restrict ptr, size_t size, size_t nobj, FILE *restrict fp);
Both return: number of objects read or written

使用说明

unsigned char *str_buf;
str_buf=(char *)malloc(sizeof(char));
*str_buf='a';
fwrite(str_buf,sizeof(char),5,fp);

运行结果

unsigned char *str_buf;
str_buf=(unsigned char *)malloc(sizeof(unsigned char));
*str_buf='a';
int i;
for(i=0;i<5;i++)
   fwrite(str_buf,sizeof(unsigned char),1,fp);

运行结果

原文地址:https://www.cnblogs.com/daijkstra/p/4057073.html