简单的文件读写函数举例

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值