C语言中的二进制I/O:fread、fwrite

    在链接:利用标准C库函数进行文件读写中介绍了使用getc或putc一次读写一个字符和使用fgets或fputs一次读写一行。

    但是如果进行二进制文件I/O操作,我们更愿意一次读写一个完整的结构。如果使用getc或putc那么必须循环通过整个结构,每次循环处理一个字节会非常麻烦而且耗时。如果使用fputs和fgets,那么因为fputs在遇到NULL字节时就停止,而在结构中可能含有NULL字节,所以不能使用它实现°结构要求。类似的如果输入数据中含有NULL字节或换行符,则fgets也不能正确工作。可以使用下面两个函数执行二进制I/O操作。 

1、fread

size_t fread( 
   void* buffer, 
   size_t size, 
   size_t count, 
   FILE* stream 
);

(1)参数

buffer:存放读的数据

size:读的结构的字节数。例如若读的数据类型为int,则size应为sizeof(int),若为结构struct{}item;则size应为sizeof(item);

count:最多读的数据数

(2)返回值

返回读的对象数。但是如果出错或者到达文件尾端,则此数字可以少于count;此时应该调用ferror或feof判断是哪一种情况。

2、fwrite  

size_t fwrite( 
   const void* buffer, 
   size_t size, 
   size_t count, 
   FILE* stream 
);
(1)参数

buffer:要写的数组地址,注意为const的

(2)返回值

返回写的对象数,若返回值少于要求的count,则出错。

 3、fread/fwrite使用 示例

(1)读或写一个二进制数组

 例如;将一个浮点数组的第2~5个元素写至FILE *fp所指的文件上。

float data[10];
if(fwrite(&data[2],sizeof(float),4,fp)!=4)
  cout<<"fwrite error"<<endl;
(2)读或写一个结构

struct(
short count;
char name[10];
}item;

if(fwrite(&item,sizeof(item),1,fp)!=1)
  cout<<"fwrite error"<<endl;
指定size为结构长度,count为1(要写的对象个数)
(3)

/* FREAD.C: This program opens a file named FREAD.OUT and
 * writes 25 characters to the file. It then tries to open
 * FREAD.OUT and read in 25 characters. If the attempt succeeds,
 * the program displays the number of actual items read.
 */

#include <stdio.h>

void main( void )
{
   FILE *stream;
   char list[30];
   int  i, numread, numwritten;

   /* Open file in text mode: */
   if( (stream = fopen( "fread.out", "w+t" )) != NULL )
   {
      for ( i = 0; i < 25; i++ )
         list[i] = (char)('z' - i);
      /* Write 25 characters to stream */
      numwritten = fwrite( list, sizeof( char ), 25, stream );
      printf( "Wrote %d items\n", numwritten );
      fclose( stream );

   }
   else
      printf( "Problem opening the file\n" );

   if( (stream = fopen( "fread.out", "r+t" )) != NULL )
   {
      /* Attempt to read in 25 characters */
      numread = fread( list, sizeof( char ), 25, stream );
      printf( "Number of items read = %d\n", numread );
      printf( "Contents of buffer = %.25s\n", list );
      fclose( stream );
   }
   else
      printf( "File could not be opened\n" );
}
输出结果:

Wrote 25 items
Number of items read = 25
Contents of buffer = zyxwvutsrqponmlkjihgfedcb


猜你喜欢

转载自blog.csdn.net/zxx910509/article/details/56846543