#include<stdio.h>
#include<stdlib.h>
#define SIZE 4
#define FILENAME "person"
struct person
{
int id;
char name[10];
};
int main()
{
void copyContent(char inFileName[], char outFileName[]);
void savePerson(struct person psons[], int size, char fileName[]);
void readPerson(struct person psons[], int size, char fileName[]);
char inFileName[] = "abc.txt";
char outFileName[] = "abc2.txt";
copyContent(inFileName, outFileName);
int i, size = SIZE;
char fileName[] = FILENAME;
struct person psons[4];
for(i = 0 ; i < size ; i ++ )
{
scanf("%d%s", &psons[i].id, psons[i].name) ;
}
savePerson(psons, size, fileName);
struct person results[4];
readPerson(results, size, fileName);
for(i = 0 ; i < size ; i ++)
{
printf("%d %s\n", results[i].id, results[i].name);
}
}
//copy file content
void copyContent(char inFileName[], char outFileName[])
{
FILE *inFile, *outFile;
char ch;
if((inFile = fopen(inFileName, "r")) == NULL)
{
printf("Cannot open inFile\n");
exit(0);
}
if((outFile = fopen(outFileName, "w")) == NULL)
{
printf("Cannot open outFile\n");
exit(0);
}
while( ! feof(inFile))
{
ch = fgetc(inFile);
fputc(ch, outFile);
putchar(ch);
}
fclose(inFile);
fclose(outFile);
}
//save struct content to file
void savePerson(struct person psons[], int size, char fileName[])
{
FILE* fp;
int i;
if((fp = fopen(fileName, "wb")) == NULL)
{
printf("Cannot open file\n");
exit(0);
}
for(i = 0 ; i < size ; i ++ )
{
if(fwrite(&psons[i], sizeof(struct person), 1, fp) != 1)
printf("file write error.\n");
}
fclose(fp);
}
//read struct content from file
void readPerson(struct person psons[], int size, char fileName[])
{
FILE* fp;
int i;
if((fp = fopen(fileName, "rb")) == NULL)
{
printf("Cannot open file\n");
exit(0);
}
for(i = 0 ; i < size ; i ++ )
{
if(fread(&psons[i], sizeof(struct person), 1, fp) != 1)
printf("Cannot open file\n");
}
fclose(fp);
}