C++的文件读写就是用用fstream、ifstream和ofstream类
1.头文件:<fstream>
2.三个类
fstream:I/O流 默认读写打开文件
ifstream:I流 默认以读打开文件
ofstream:O流 默认以写打开文件
3.打开文件
方式一:实例化fstream类时默认打开
如:
fstream file(filename, mode); 默认读写打开文件ios::in::ios::out 当文件不存在时不会创建
ifstream file(filename, mode); 默认以读打开文件ios::in
ofstream file(filename, mode); 默认以写打开文件ios::out Not:当文件不存在时会创建
方式二:显示调用open函数
fstream file;
file.open(filename, mode);
4.判断文件是否存在
利用ifstream 打开文件失败即为文件不存在
ifstream file(filename);
if( file.good() ){
cout << "file exist" << endl;
}
5.创建文件
利用ofstream 打开 当文件不存在时会创建
ofstream file(filename);
6.写文件
方式一:<<
ofstream file(filename);
file << msg; //<<将msg通过file这个文件输出流写到文件中
方式二:write
const char *msg = "I am Bob!";
file.write(msg, strlen(msg));
7.读文件
读之前注意此时文件指针位于何处
可用file.tellg() file.tellp() 查询
也可用file.seekg(n, post) file.seekp(n, post) 设置
方式零:使用 >>
方式一:逐个字符的读:get
方式二:逐行的读:getline
方式三:指定读多少:read
8.判断文件是否打开
ret = file.is_open();
if( ret )
cout << "Is open" << endl;
9.关闭文件
file.close()
10.demo:
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
const char *filename = "D:\\tst.doc";
int main(int argc, char **argv)
{
//文件IO
//write file and create
ofstream fileout(filename);
if (!fileout.good()) {
cout << "open file failed!" << endl;
exit(EXIT_FAILURE);
}
else
cout << "open file successful!" << endl;
const char *msg = "I am Bob!";
fileout.write(msg, strlen(msg));
//file << "I am Carl!";
fileout.close();
//read file
ifstream filein(filename);
if (!filein) {
cout << "file not exist" << endl;
exit(EXIT_FAILURE);
}else
cout << "file have exist" << endl;
//way0:get a string use >>
//string str;
//while ( filein.peek() != EOF ) {
// filein >> str; //以空格或、换行或结尾标示,为一次读取,要自己做分割符
// cout << str;
// str.clear();
// cout << " ";
//}
//way1:get a char use filein.get()
//char c;
//while ( filein.peek() != EOF ) {//peek() 获取下一个字符的值,但不会移动文件指针
// c = filein.get(); //可以读取空格
// cout << c;
//}
//way3:get a strline use filein.getline()
/* char buff[69];
while ( filein.peek() != EOF) {
memset(buff, 0, sizeof(buff));
filein.getline(buff, sizeof(buff));
cout << buff;
}*/
//way4:get some string use filein.read()
char buff[69];
while ( filein.peek() != EOF ) {
memset(buff, 0, sizeof(buff));
filein.read(buff, sizeof(buff));
cout << buff;
}
filein.close();
return 0;
}