Use fwrite and fread to save and read : File fwrite fread « File « C / ANSI-C






Use fwrite and fread to save and read

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  FILE *fp;
  int i;

  /* open file for output */
  if((fp = fopen("my.txt", "wb"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }

  i = 100;

  if(fwrite(&i, 2, 1, fp) != 1) { 
    printf("Write error occurred.\n");
    exit(1);
  }
  fclose(fp);

  /* open file for input */
  if((fp = fopen("myfile", "rb"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }

  if(fread(&i, 2, 1, fp) != 1) {
    printf("Read error occurred.\n");
    exit(1);
  }
  printf("i is %d", i);
  fclose(fp);

  return 0;
}

           
       








Related examples in the same category