fread syntax
int fread(void *buffer , int size_of_1_unit , int count ,FILE *fin);
ถ้า fread ทำงานสำเร็จ จะทำการคืนค่าจำนวนที่อ่านได้ทั้งหมด ดังนั้นเราสามารถเช็กได้เช่น
if (fread( myArray, sizeof(double) , MAX , fin ) == MAX )
{
// แสดงว่าทำงานสำเร็จ
}
fwrite syntax
int fwrite(void *buffer , int size_of_1_unit , int count ,FILE *fout);
ถ้า fwrite ทำงานสำเร็จ จะทำการคืนค่าจำนวนที่เขียนได้ทั้งหมด ดังนั้นเราสามารถเช็กได้เช่น
if (fwrite ( myArray, sizeof(double) , MAX , fin ) == MAX )
{
// แสดงว่าทำงานสำเร็จ
}
- การเปิดแบบ binary mode ให้ทำการเพิ่มอักษร b หลังจากโหมดปกติ เช่น “ab” , “rb” , etc…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <math.h> | |
#define MAX 30 | |
int main(void) | |
{ | |
setbuf(stdout,NULL); | |
char *fileName = "myArray.txt"; | |
double a[MAX] ; | |
int i; | |
for(i = 0 ; i < MAX ;i++) | |
{ | |
a[i] = sqrt(i); | |
} | |
FILE *fout = fopen(fileName,"wb"); | |
if(fout == NULL) exit(-1); | |
fwrite(a,sizeof(double) ,MAX , fout); | |
fclose(fout); | |
FILE *fin = fopen(fileName,"rb"); | |
if(fin == NULL) exit(-1); | |
double b[MAX]; | |
fread( b, sizeof(double), MAX , fin ); | |
for(i = 0 ; i < MAX ;i++) | |
{ | |
printf("%d : %f\n",i,b[i]); | |
} | |
fclose(fin); | |
return 0; | |
} |