C++中的文件流


ifstream用来从磁盘文件的输入

ofstream用来向磁盘文件的输出

fstream既可以用来输入也可以用来输出

1.向文件中写入

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    ifstream ifs/*("hello.txt")*/;//可以在常见这个变量时就初始化
    char buf[100];
    ifs.open("hello.txt",ios::in/*表明是写入的状态,不写的化默认也是写入的状态*/);//也可以后来对他进行初始化
    if(!ifs)
    {
        cout<<"open feiled"<<endl;
    }
    ifs>>buf;//将ifs文件中的内容写入到buf中去
    //ifs.getline(buf,100);
    cout<<buf<<endl;
}

2.将文件中的内容如初到屏幕上

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    ofstream ofs;
    ofs.open("hello.txt"/*不写默认是读出的状态*/);
    if(!ofs)
    {
        cout<<"失败阿"<<endl;
    }
    char buffer[100]="asdfasdfasdfa";
    ofs<<buffer;//将buffer中的内容如初到ofs当中去
    ofs.close();//有open必须要有close();
    return 0;
}



猜你喜欢

转载自blog.csdn.net/zzw_17805056819/article/details/80167641
今日推荐