Code Snippets C

//Header file: #include
//Declaration: size_t fread(void *buf, size_t size, size_t count, FILE *stream);
//Return: returns the number of items actually read.
#include
#include
int main(void)
{
FILE *filep;
float bal[5] = { 2.3F, 3.6F, 3.3F, 4.8F, 5.5F };
int i;
if((filep=fopen("testfile", "wb"))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
if(fwrite(bal, sizeof(float), 5, filep) != 5)
printf("File read error.");
fclose(filep);
if((filep=fopen("testfile", "rb"))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
if(fread(bal, sizeof(float), 5, filep) != 5) {
if(feof(filep)) {
printf("Premature end of file.");
}else {
printf("File read error.");
}
}
fclose(filep);
for(i=0; i<5; i++){
printf("%f ", bal[i]);
}
return 0;
}
/*
2.300000 3.600000 3.300000 4.800000 5.500000 */