繁体   English   中英

一次性读取完整文件是个好主意吗?

[英]Is it a good idea to read full file in one shot?

我正在拍摄完整的文件,也是电影文件。 然后我使用该缓冲区写入一个像50KB的新文件。 纠正我这是错的? 以下是示例代码:

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);

在你有足够的可用内存之前它是有用的......但是要注意,如果文件大于4GB而你使用的是32位编译器。

流读取器模型用于读取文件,因为文件大小没有限制,但您可以使用内存限制。 如果您的文件大小足够小以完全存储在内存中没有问题,但如果您正在读取媒体文件,例如4GB + DVD ISO,我认为您的程序将消耗太多内存,并且无法在低规格计算机上运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM