C语言文件IO操作

函数原型:

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

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

示例代码:

/* fread example: read an entire file */
#include 
#include 

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点击打开链接

你可能感兴趣的:(C基础知识)