Reading, writing, rewind the file pointer of the binary data file using fopen_s()/fopen(), fread(), fwrite() and rewind() C functions
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows Xp Pro with SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)
Other info:
To do: To read, write, rewind file pointer of the binary data file using fopen_s()/fopen(), fread(), fwrite() and rewind() C functions
To show: Steps on how to read, write, rewind file pointer of the binary file content using fopen_s()/fopen(), fread(), fwrite() and rewind() C functions
// Reading, writing, rewind the binary file
#include <stdio.h>
#include <stdlib.h>
enum {SUCCESS, FAIL, MAX_NUM = 5};
// functions prototypes...
void DataWrite(FILE *fout);
void DataRead(FILE *fin);
int ErrorMsg(char *str);
int main(void)
{
FILE *fptr;
errno_t err = 0;
// binary type files...
char filename[] = "c:\\teseight.bin";
int reval = SUCCESS;
// test for creating, opening binary file for writing...
// fopen(filename, "wb+"), but using a secure version
err = fopen_s(&fptr, filename, "wb+");
if(err != 0)
{
reval = ErrorMsg(filename);
}
else
{
// Write data into file teseight.bin
DataWrite(fptr);
// reset the file position indicator...
rewind(fptr);
// read data...
DataRead(fptr);
// close the file stream...
if(fclose(fptr)==0)
printf("%s successfully closed\n", filename);
}
return reval;
}
// DataWrite() function definition
void DataWrite(FILE *fout)
{
int i;
double buff[MAX_NUM] = { 145.23, 589.69, 122.12, 253.21, 987.234};
printf("I\'m in DataWrite, doing my job, writing...\n");
printf("The size of buff: %d-byte\n", sizeof(buff));
for(i=0; i<MAX_NUM; i++)
{
printf("%5.2f\n", buff[i]);
fwrite(&buff[i], sizeof(double), 1, fout);
}
}
// DataRead() function definition
void DataRead(FILE *fin)
{
int i;
double x;
printf("I\'m in DataRead(), reading...");
printf("\nRe-read from the binary file:\n");
for(i=0; i<MAX_NUM; i++)
{
fread(&x, sizeof(double), (size_t)1, fin);
printf("%5.2f\n", x);
}
}
// ErrorMsg() function definition
int ErrorMsg(char *str)
{
printf("I\'m in ErrorMsg(), doing my job if needed.\n");
printf("Cannot open %s.\n", str);
return FAIL;
}
Output example:
I'm in DataWrite, doing my job, writing...
The size of buff: 40-byte
145.23
589.69
122.12
253.21
987.23
I'm in DataRead(), reading...
Re-read from the binary file:
145.23
589.69
122.12
253.21
987.23
c:\teseight.bin successfully closed
Press any key to continue . . .