看了一下C++中关于文件的介绍,现在主要将其整理一下,并且给出使用较为简单的函数来处理相应的文件。C++中的文件主要分为两类:文本文件和二进制文件,其主要区别就是文本文件是以ASCII码的形式存储的,因此存储的时候每一个字符都要占据一个字节,所以占用内存空间比较大,但是是可读文件;而二进制文件存储的时候是将二进制码照原样输出到磁盘文件中,因此不具有可读性,但是占用空间较小。
文件流类主要有三种形式:输出文件流ofstream,输入文件流ifstream,输入输出文件流fstream.
对于文本文件主要的处理函数:
1)get(),put(),以单个字符的形式处理文件
2)getline(char *buf,int limit,char deline='\n')以字符数组的形式读文件。
对于二进制文件的处理函数:read(char *buf,int size)读文件函数,write(const *buf,int size)写文件。
下面是我自己写的关于文件处理的代码:主要实现将包含学生学号、姓名、成绩的信息输入到文件stu_info.dat中,然后读该文件并将学生信息打印到屏幕上,并将文件拷贝到stu_info1.dat中;
#include "stdafx.h"
#include <iostream>//编译预处理命令,输入输出流文件
#include <fstream>
#include <iomanip>
#include <math.h>
#include <string.h>
#include <strstream>
using namespace std;
struct stu
{
int num;
char name[20];
float score;
};
void main()
{
int n;
char a;
stu *p;
int i;
cout<<"input the number of stu:";
cin>>n;
p=new stu[n];
for(i=0;i<n;i++)
cin>>p[i].num>>p[i].name>>p[i].score;
ofstream out("E:\\stu_info.dat",ios::out);
//wirte
for(i=0;i<n;i++)
out<<p[i].num<<'\t'<<p[i].name<<'\t'<<p[i].score<<endl;
delete [] p;
out.close();
ifstream in("E:\\stu_info.dat",ios::in);
ofstream out1("E:\\stu_info1.dat",ios::out);
if(!in)
{
cout<<"can't open the file"<<endl;
abort();
}
while(!in.eof())//judge the end of file
{
in.get(a);
cout<<a;
out1.put(a);//copy the file
}
in.close();
out1.close();
}
程序运行结果如下: