c++文件输入与输出 原创 五毛钱小编 2022-06-11 15:17:02 博主文章分类:编程语言 ©著作权 文章标签 c++ 阅读量: 次 ©著作权归作者所有:来自云都学院作者五毛钱小编的原创作品,请联系作者获取转载授权,否则将追究法律责任c++文件输入与输出http://www.yundu.com/blog/188.html ## 基于流的文件IO [头文件](https://so.csdn.net/so/search?q=%E5%A4%B4%E6%96%87%E4%BB%B6&spm=1001.2101.3001.7020) ofstream : 写文件 ifstream : 读文件 fstream : 读写文件 ``` using namespace std; //打开文件 std::ifstream fin("xxx.txt"); //std::ifstream fin; //fin.open("xxx.txt"); std::ofstream fout("xxxx.txt"); if (!fin.is_open()) //判断文件是否打开成功 { cout << "打开文件异常" << endl; fin.clear(); } //从文件读取一个字符 char ch; fin >> ch; //read a character from the file char buf[80]; fin >> buf; //read a word from the file fin.getline(buf, 80); //read a line from the file string line; getline(fin, line); //read from a file to a string object fout<< line; fout.close(); fin.close(); fin.clear(); //reset fin ``` - **文件模式** 将流与文件关联时(无论所雇佣文件名初始化文件流对象,还是使用open()方法),都可以指定文件模式第二个参数: ifstream fin(“xxxxx.txt”,openMode1); ofstream fout(); fout.open(“xxxxx.txt”,openMode2); | 常量 | 含义 | | --- | --- | | ios\_base::in | 打开文件,以便读取 | | ios\_base::out | 打开文件,以便写入 | | ios\_base::ate | 打开文件,并移到文件尾 | | ios\_base::app | 追加到文件尾 | | ios\_base::trunc | 如果文件存在,截断文件(清空旧文件) | | ios\_base::binary | 二进制文件 | ifstream open()方法和构造函数用ios\_base::in(打开文件以读取)作为模式参数的默认值,而ofstream open()方法和构造函数用 ios\_base::out|ios\_base::trunc(打开文件,以写入并截断文件)作为默认参数。位运算符or(|)用于将两个位值合并成为一个可用于设置两个位的值。 - **c++mode与cmode对应关系** | c++模式 | c模式 | 含义 | | --- | --- | --- | | ios\_base::in | “r” | 打开以读取 | | ios\_base::out|ios\_base::trunc | “w” | 打开以写入,如果已存在,则覆盖 | | ios\_base::out|ios\_base::app | “a” | 打开以写入,只追加 | | ios\_base::out|ios\_base::out | “r+” | 打开以读写,在文件允许的位置写入 | | ios\_base::out|ios\_base::out|ios\_base::trunc | “w+” | 打开以读写,如果已存在,首先覆盖 | | c++mode|ios\_base::binary | “cmode”+“b” | 以c++mode(或相应cmode)和二进制模式打开;例如:ios\_base::in|ios\_base::binary成为"rb" | | c++mode|ios\_base::ate | “cmode” | 以指定模式打开,并移到文件尾。C是使用一个独立的函数调用,而不是模式编码。例如:ios\_base::in|ios\_base::ate 被转换为"r"模式打开,然后调用fseek(file,0,SEEK\_END) | 注意:ios\_base::ate和ios\_base::app都将文件指针指向打开的文件末尾。二者的区别在于,ios\_base::app模式只允许将数据添加到文件末尾,而ios\_base::ate模式是将指针放到文件尾。 分享 微博 QQ 微信 上一篇:【 C++入门 】函数重载、extern“C“ 下一篇:没有了