C语言文件IO操作

函数原型:

size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );       所在头文件 : <cstdio>

Read block of data from stream  从文件流中读取count个元素,元素的大小是size字节,存储到ptr所指向的内存单元。读取的过程中文件指针做相应的移动。成功读取返回总共读取的字节数。

示例代码:

/* fread example: read an entire file */
#include <stdio.h>
#include <stdlib.h>

int main () {
  FILE * pFile;
  long lSize;
  char * buffer;
  size_t result;

  pFile = fopen ( "myfile.bin" , "rb" );
  if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

  // obtain file size:
  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

  // allocate memory to contain the whole file:
  buffer = (char*) malloc (sizeof(char)*lSize);
  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

  // copy the file into the buffer:
  result = fread (buffer,1,lSize,pFile);
  if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

  /* the whole file is now loaded in the memory buffer. */

  // terminate
  fclose (pFile);
  free (buffer);
  return 0;
}

long int ftell ( FILE * stream ); 返回当前文件指针的位置。

int fseek ( FILE * stream, long int offset, int origin ); 将文件指针设置到新的位置对于二进制模式打开的文件,新的文件位置是 offset + origin

SEEK_SET    Beginning of file
SEEK_CUR   Current position of the file pointer
SEEK_END    End of file *

int sscanf ( const char * s, const char * format, ...);  工作原理类似scanf,不过是从字符串s中读取安装format的格式进行处理,结果保存在变参中。

char * fgets ( char * str, int num, FILE * stream );
从文件中最多 读取num - 1 个字符,自动填充字符串结尾的‘\0’。 遇到'\n'后停止,'\n'也被认为是一个合法字符存储在str中。

示例代码

#define BUFSIZE 1024
int main(int argc, char** argv)
{
  int newlines = 0;
  char buf[BUFSIZE];
  FILE* file;

  if (argc != 2)
  {
  	printf("usage error!\n");
    return 1;
  }

  file = fopen(argv[1], "r");
  if (NULL == file)
  {
  	printf("Open file error! [ %s ]\n", argv[1]);
	return -1;
  }
  while (fgets(buf, BUFSIZE, file))
  {
   if (!(strlen(buf) == BUFSIZE-1 && buf[BUFSIZE-2] != '\n'))
      newlines++;
	
  }

  printf("Number of lines in %s: %d\n", argv[1], newlines);

  return 0;
}


参考资料

http://www.cplusplus.com/reference/cstdio/fgets/?kw=fgets点击打开链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值