ファイルの内容を全てメモリに取り込む

戻る
#include <stdio.h>
/**
* $Id: fread-test.html,v 1.1 2009/06/22 16:12:10 kishi Exp kishi $
*/

int
main (void)
{
  FILE *fp;
  const char *filename = "fread-test.c";
  size_t size;
  char *buf;

  fp = fopen (filename, "r");
  if (fp == NULL) {
    fprintf (stderr, "cannot open %s\n", filename);
    return -1;
  }

  fseek (fp, 0L, SEEK_END);	// ファイルポインタを最後尾へ移動
  size = ftell (fp);		// ファイルサイズを取得

  printf ("ファイルサイズは、%d です。\n", size);

  fseek (fp, 0L, SEEK_SET);	// ファイルポインタを先頭へ移動

  buf = (char *) malloc (size);
  printf ("address of buf = %08x\n", buf);

  int n = 1;
  fread (buf, size, n, fp);

  fclose (fp);

/* make sure what is contained in buffer */
  printf ("\n");

//  char *p = buf;
//  int i;
//  for (i = 0; i < size; i++) {
//    printf ("%c", *p++);
//  }

  fwrite (buf, size, n, stdout);

  printf ("\n");

  return 0;

}

戻る

inserted by FC2 system