#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mytest001.h"
char s_char_buf[LEN_PERSON + 1] = "\0";
int s_int_len = 0;
/*
* write records to file
*/
void writeRecordToFile() {
printf("--------------------------------writeRecordToFile()\n");
/* 1. prepare data */
Person personArr[3];
/* clear the memory. not needed??? */
memset(personArr, NULL, sizeof(Person) * 3);
/* NOTICE : sprintf() will asign personArr[0].sex[0] to NULL;
* so, the following asign sentense must following the order declared in
* structure <Person>.
*/
sprintf(personArr[0].name, "%20s", "mp3");
sprintf(personArr[0].sex, "F");
sprintf(personArr[0].mail, "%20s", "[email protected]");
sprintf(personArr[0].age, "%03d", 25);
sprintf(personArr[0].job, "%10s", "std");
personArr[0].end = '\n'; /* NULL -> '\n' */
sprintf(personArr[1].name, "%20s", "mp4");
sprintf(personArr[1].sex, "M");
sprintf(personArr[1].mail, "%20s", "[email protected]");
sprintf(personArr[1].age, "%03d", 26);
sprintf(personArr[1].job, "%10s", "emp");
personArr[1].end = '\n';
sprintf(personArr[2].name, "%20s", "mp5");
sprintf(personArr[2].sex, "F");
sprintf(personArr[2].mail, "%20s", "[email protected]");
sprintf(personArr[2].age, "%03d", 27);
sprintf(personArr[2].job, "%10s", "mgr");
personArr[2].end = '\n';
/* 2. open file */
FILE* outFile = fopen("out_EN.txt", "wb");
/* 3. open error check */
if (NULL == outFile) {
/* ERROR handle */
perror("Unable open file for reading.\n");
}
/* 4. write records to file */
int i = 0;
int errFlag = 0;
for (i = 0; i < 3; i++) {
size_t writtenBytes = fwrite(&personArr[i], LEN_PERSON, 1, outFile);
/* 4.1 IO error check */
if (0 == writtenBytes) {
/* ERROR handle */
errFlag = 1;
break;
}
}
/* 5. close stream */
fclose(outFile);
/* 6. message */
if (errFlag) {
perror("Error occured while writing record to file.\n");
} else {
printf("Writing record to file succeed.\n");
}
}
void readRecordFromFile() {
printf("--------------------------------readRecordFromFile()\n");
Person p;
/* 1. open file */
FILE* inFile = fopen("out_EN.txt", "rb");
/* 2. open error check */
if (NULL == inFile) {
/* ERROR handle */
perror("Unable open file for reading.\n");
}
/* 3. read records from stream */
int errFlag = 0;
size_t readBytes = 0;
readBytes = fread(&p, LEN_PERSON, 1, inFile);
while (0 != readBytes) {
/* 3.1 handing records(here just print it to stdout) */
p.end = NULL; /* '\n' -> NULL */
printf("%s\n", (char *)&p);
readBytes = fread(&p, LEN_PERSON, 1, inFile);
}
/* 3.2 IO error check */
if (ferror(inFile)) {
/* ERROR handle */
errFlag = 1;
}
/* 4. close stream */
fclose(inFile);
/* 5. message */
if (errFlag) {
perror("Error occured while reading record from file.\n");
} else {
printf("Reading record from file succeed.\n");
}
}
|