当前位置:编程学习 > C/C++ >>

操作系统大型实验进展(8)-----C语言函数fread

C语言库函数名:
简介
  函数原型:
  size_t fread(void *buffer, size_t size, size_tcount, FILE *stream); 
  功 能:
  从一个文件流中读数据,读取count个元素,每个元素size字节.如果调用成功返回count.如果调用成功则实际读取size*count字节
  参 数:
  buffer
  用于接收数据的内存地址,大小至少是size*count 字节.
  size
  单个元素的大小,单位是字节
  count
  元素的个数,每个元素是size字节.
  stream
  输入流
  返回值:
  实际读取的元素数.如果返回值与count(不是count*size)不相同,则可能文件结尾或发生错误.
  从ferror和feof获取错误信息或检测是否到达文件结尾.
程序例
  #include <stdio.h>
  #include <string.h>
  int main(void)
  {
  FILE *stream;
  char msg[] = "this is a test";
  char buf[20];
  if ( (stream = fopen("DUMMY.FIL", "w+")) == NULL) {
  fprintf(stderr,"Cannot open output file.\n");
  return 1;
  } /* write some data to the file */
  fwrite(msg, 1,strlen(msg)+1, stream); /* seek to the beginning of the file */
  fseek(stream, 0, SEEK_SET); /* read the data and display it */
  fread(buf, 1,strlen(msg)+1,stream);
  printf("%s\n", buf);
  fclose(stream);
  return 0;
  }
MSDN示例
  #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" );
  }
 
补充:软件开发 , C语言 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,