C中的文件处理相关知识


最近在写数据结构的实验时,要用到存储和读取文本文件的操作,于是我回顾了一下在上个学期学习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;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值