#include "stdafx.h"
#include<iostream>
#define SIZE 2
#define CULL 1
#define OPEN_FILE_ERROR 0
#define READ_FILE_ERROR -1
#define WRITE_FILE_ERROR -2
using namespace std;
typedef struct
{
int id;
int age;
char name[20];
char addr[20];
}STU;
int save(STU * fstd)
{
FILE * fp = NULL;
if((fp=fopen("gaoyin.txt","a")) == NULL)
{
cout<<"Open file error"<<endl;
return OPEN_FILE_ERROR;
}
if(fwrite((void*)fstd,sizeof(STU),1,fp)!=1)
{
cout<<"write file error"<<endl;
fclose(fp);
return WRITE_FILE_ERROR;
}
fclose(fp);
return CULL;
}
int reads(STU * fstd)
{
FILE * fp = NULL;
if((fp=fopen("gaoyin.txt","rb")) == NULL)
{
cout<<"read file error"<<endl;
return READ_FILE_ERROR;
}
for(int i=0;i<SIZE;i++)
{
if(fread((fstd+i),sizeof(STU),1,fp) != 1)
{
cout<<"read file error"<<endl;
return READ_FILE_ERROR;
}
}
fclose(fp);
}
int _tmain(int argc, _TCHAR* argv[])
{
STU studentArray[SIZE]={{0}};
//for(int i=0;i<SIZE;i++)
//{
// cout<<"Please input student info : ";
// cin>>studentArray[i].id>>studentArray[i].age>>studentArray[i].name>>studentArray[i].addr;
// save(&studentArray[i]);
// cout<<"over save"<<endl;
//}
reads(studentArray);
for(int i=0;i<SIZE;i++)
{
cout<<studentArray[i].id<<" "<<studentArray[i].age<<" "<<studentArray[i].name<<" "<<studentArray[i].addr<<endl;
}
system("pause");
return 0;
}
fgetc,fputc举例:
#include "stdafx.h"
#include<iostream>
using namespace std;
#define OPEN_FILE_ERROR -1
#define CULL 0
int save()
{
char ch;
FILE * fp = NULL;
if((fp=fopen("gaoyin.txt","w")) == NULL)
{
cout<<"Open file error"<<endl;
return OPEN_FILE_ERROR;
}
while((ch=getchar()) != '#')
{
putchar(ch);
fputc(ch,fp);
}
fclose(fp);
return CULL;
}
int load()
{
FILE * fp1 = NULL;
FILE * fp2= NULL;
if((fp1=fopen("gaoyin.txt","r")) == NULL)
{
cout<<"Open file error"<<endl;
return OPEN_FILE_ERROR;
}
if((fp2=fopen("loadtest.txt","w")) == NULL)
{
cout<<"Open file error"<<endl;
return OPEN_FILE_ERROR;
}
while(!feof(fp1))
{
fputc(fgetc(fp1),fp2);
}
fclose(fp2);
fclose(fp1);
return CULL;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"Please input chars ‘#’to end : ";
save();
load();
system("pause");
return 0;
}