c++写文件操作

c++写文件操作

#include<iostream>
#include<fstream>//操作文件的头文件
#include<string>
using namespace std;
void ofstr()
{
    
    
    ofstream ofs;						//定义流对象
    ofs.open("text.txt",ios::out);		//以写的方式打开文件
    ofs<<"woshichuhh"<<endl;//写入
    ofs<<"forever"<<endl;
    ofs<<"woshichuhh"<<endl;
    ofs.close();
}
void ifstr()
{
    
    
    ifstream ifs;
    ifs.open("text.txt",ios::in);		//以读的方式打开文件
    if(!ifs.is_open())					//判断是否打开成功
    {
    
    
        cout<<"open failed"<<endl;
        return ;
    }
    //----one----//
	char buf[1024]={
    
    0};					//有四种方法读出
    while(ifs>>buf)
    {
    
    
        cout<<buf<<endl;
    }
    // //----two----
    // char buf[1024]={0};
    // while(ifs.getline(buf,sizeof(buf)))
    // {
    
    
    //     cout<<buf<<endl;
    // }
    //----three----
    // string buf;
    // while(getline(ifs,buf))
    // {
    
    
    //     cout<<buf<<endl;
    // }
    // //----four----
    // char c;
    // while((c=ifs.get())!=EOF)
    // {
    
    
    //     cout<<c;
    // }
    ifs.close();						//关闭文件指针
}
int main()
{
    
    
    ofstr();
    ifstr();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/WCvison/article/details/114890035