2

使い方が分からず困ってfread()います。以下はcplusplus.comの例です。

/* fread example: read a complete 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;
}

私はまだ使っていないとしましょうfclose()。配列として扱いbuffer、のような要素にアクセスできますbuffer[i]か? それとも何か他のことをしなければなりませんか?

4

1 に答える 1

4

もちろん、freadデータを呼び出すと、実際にはバッファ内にコピーされます。ファイルを安全に閉じて、バッファ自体で必要なことを行うことができます。

バッファを変更して元のファイルにアクセスできるかどうかを尋ねたときに、答えが「いいえ」の場合は、ファイルを書き込みモードで開き、fwrite.

たとえば、2 つの浮動小数点数、1 つの int、および 16 文字の文字列を含むバイナリ ファイルがある場合、構造体を簡単に定義できます。

struct MyData
{
  float f1;
  float f2;
  int i1;
  char string[16];
};

そしてそれを直接読んでください:

struct MyData buffer;
fread(&buffer, 1, sizeof(struct MyData), file);
.. buffer.f1 ..
于 2012-04-05T23:25:55.203 に答える