最近在写数据结构的实验时,要用到存储和读取文本文件的操作,于是我回顾了一下在上个学期学习C++文件处理的时候,我用到的是创建文件类,创建对象对文件进行操作。
而C对文件的操作核心上离不开指针的运用。
C++操作是对对象的操作,因此首先应该创建写文件流的对象,即ofstream ofile ,对对象的操作都是通过方法实现的。
而在C中,是通过文件指针 FILE *fp 和对应的库函数 fopen close fputs.... 来实现的,其中fopen也包含写操作文件的名称和文件操作方式这两大参数。
C文件操作,下面是我写的一个例子,1.创建FILE指针 2.fopen打开文件 3.判断是否创建或打开成功 4.分配内存空间读写操作 5.关闭!
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
int main(){
FILE *F;
char *str;
F = fopen("lalal.txt","r");
//用到fgets 读取字符串
if(!F) cout<<"打开失败或者创建失败"<<endl;
else{
// str = (char*)malloc(sizeof(char)*100);//分配空间
str = new char[256];
fgets(str,99,F);
fgets(str+strlen(str),99,F);
if(str)
cout<<str;
// char ch ;
// while(!feof(F)){
// ch = fgetc(F);
// cout<<ch;
// }
}
return 0 ;
}
我使用了两种方式分配内存空间,一种是C的方法一种是C++的方法。
C++:我创建了两个类,一个是文件输出类一个是文件输入类。
class Ofile{//创建一个文件输出类
private:
string file_name;
static int count;//创建静态变量用于计数
public:
ofstream ofile;
Ofile(string);
template<typename T>//用函数 模板实现
void add_class(T& m){
this->ofile.write((char*)&m,sizeof(T));
}
static int show_count(){//写一个静态方法返回文件类创建次数
return Ofile::count;
}
void set_file(string name){//用方法关联文件流
this->ofile.open(name.c_str(),ios::out|ios::binary);
}
void set_securer();
void set_cleaner();
void set_maintenancer();
// void add_class(securer& m);
// void add_class(cleaner& m);
};
int Ofile::count = 0;
Ofile::Ofile(string filename){
this->ofile.open(filename.c_str(),ios::out|ios::binary);
Ofile::count++;
}
void Ofile::set_maintenancer(){
cout<<"工程师文件流正在输出"<<endl;
}
class Ifile{//创建一个文件输入类
private:
string file_name;
static int count;
public:
ifstream ifile;
Ifile(string filename){
this->ifile.open(filename.c_str(),ios::in|ios::binary);
Ifile::count++;
}
template<typename T>//用函数 模板实现
// T add_class(T& a){
// T m;
// this->ifile.read((char*)&m,sizeof(T));
// return m;
//
// }
void add_class(T& a){
this->ifile.read((char*)&a,sizeof(T));
}
// securer& add_class(){
// securer m;
// this->ifile.read((char*)&m,sizeof(securer));
// return m;
// }
static int show_count(){//写一个静态方法返回文件类创建次数
return Ifile::count;
}
void set_file(string name){//用方法关联文件流
this->ifile.open(name.c_str(),ios::in|ios::binary);
}
};
int Ifile::count = 0;