基础知识
- C++对文件读写的头文件
#include<fstream>
//提供三个类
ifstream -- 从已有的文件读
ofstream -- 向文件写内容
fstream -- 打开文件供读写
- 文件类型
二进制文件:由二进制(0和1)组成的文件 | 文本文件:以字符序列组成的文件 |
---|
- 编程中填写文件路径
infile.open("D:\\codeblocks\\file.dat") //绝对路径 注意是两个斜杠
等价表示:
infile.open("D:/codeblocks/file.dat") //绝对路径 用单个反斜杠代替
//
infile.open("file.dat"); //相对路径 要求文件file 和cpp或cbp文件在同一目录
//
其他(不常用):
infile.open("..\\codeblocks\\file.dat"); //“..”表示退到当前目录的上一级目录(父目录)
infile.open(".\\codeblocks\\file.dat"); //“.”表示当前默认目录
基本操作
- 用ofstresam写文件
string str;
ifstream infile; //定义ifstream类的实例 infile
infile.open("a.dat"); //以默认方式打开a.dat
infile>>str; //读入文写的数据到str字符串
cout<<str; //打印到屏幕
2,3 行可用 ifstream infile("a.dat"); 代替。
- 用ifstresam写文件
ifstream outfile;
outfile.open("a.dat");
// ifstream outfile("a.dat");