C++文件流的写与读
1. 头文件 #include<fstream>
2. 这是头文件包含的模板 对外接口
定义了一个文件指针来指向文件流 FILE *__CLRCALL_PURE_OR_CDECL
extern _CRTIMP2_PURE FILE *__CLRCALL_PURE_OR_CDECL _Fiopen(
const char *,
ios_base::openmode, int);
extern _CRTIMP2_PURE FILE *__CLRCALL_PURE_OR_CDECL _Fiopen(
const wchar_t *,
ios_base::openmode, int);
#ifdef _NATIVE_WCHAR_T_DEFINED
extern _CRTIMP2_PURE FILE *__CLRCALL_PURE_OR_CDECL _Fiopen(
const unsigned short *,
ios_base::openmode, int);
接下来看看写入操作:
void DEMO() {
fstream file("./test.txt", ios::out);
//或者也可以 file.open("./test.txt", ios::out):
if (!file.is_open()) {
cout << "打开文件失败" << endl;
return;
}
//输入文件内 实际上是缓冲区输入
file << "姓名: 猴子" << endl;
file << "年龄: 16" << endl;
file << "性别: 男" << endl;
file.close();
}
接下来读入文件四种读法:
void DEMOFILE() {
fstream file("./test.txt", ios::in);
if (!file.is_open()) {
cout << "打开文件失败" << endl;
return;
}
//接下四种读法:
//第一种
char buf[1024] = { 0 };
while (file.getline(buf, sizeof(buf))) {
cout << buf << endl;
}
//第二种
string buf;
while (getline(file,buf)) {
cout << buf << endl;
}
//第三种
char c;
while ((c = file.get()) != EOF) {
cout << c;
}
//第四种
char buf[1024] = { 0 };
while (file>>buf) {
cout << buf ;
cout << endl;
}
file.close();
}
推荐使用第二种读入方法。
欢迎小白组队刷题: