C++读写文件,fstream

文件的读写

  • 文件读写实现的方式很多,这里简单介绍fstream,它提供了一种流的方式操作文件,用起来和cin/cout感觉一样,极易上手

头文件:

#include<fstream>

打开文件输入流:

ifstream in("test.txt");
//如果打开失败将返回0
if(!in){
    //打开失败
}

如果打开成果,就和cin一样的用法,我们看一个查找名字的程序

string name;
while(in>>name){
    if(name=="target"){
        cout<<"find "<<name<<endl;
        break;
    }
}

打开文件输出流:

//默认打开方式是覆盖,我们可以指定为追加(append),通过第二个参数
ofstream out("test.txt",ios_base::app);
if(!out){
    //打开失败
}

如果打开成功,和cout一样用法,不再演示

打开文件输入输出流:

如果想同时读写文件,打开文件输入输出流

fstream io("test.txt",ios_base::in|ios_base::app);
if(!io){
    //打开失败
}
else{
    iofile.seekg(0);
    //文件io流中有输入和输出两个指针,seekp是输出指针,seekg是输入指针
    //这里将输入定位到了文件头部
}

关闭流:

调用.close()函数即可,例如

in.close();

模式:

常用打开模式

The following constants are also defined:
Constant Explanation
app seek to the end of stream before each write
binary open in binary mode
in open for reading
out open for writing
trunc discard the contents of the stream when opening
ate seek to the end of stream immediately after open

原文链接: https://www.cnblogs.com/qishihaohaoshuo/p/12747666.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++读写文件,fstream

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/343522

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午2:09
下一篇 2023年3月2日 上午2:09

相关推荐