参考文章
该系列文章非原创,是本人在学习C++时整理他人博客的学习笔记,旨在将知识点做系统性整理,供之后复习使用。参考博客如下列出:
小甲鱼系列视频
1.C++的文件操作
1.1 ifstream对象
- ifstream对象:文件读取类
- 成员函数open()实现打开文件的操作,从而将数据流和文件进行关联。同时open为该对象的构造函数(即该对象默认使用的函数),此时可以把代码:
ifstream in;
in.open( "test.txt" ); //成员函数open()实现打开文件的操作
改为:
ifstream in( "test.txt" );
例子:
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream in;
in.open( "test.txt" ); //成员函数open()实现打开文件的操作
if( !in ){
cerr << "打开文件失败!" << endl;
return 0;
}
char x;
while( in >> x){
cout << x;
}
cout << endl;
in.close();
return 0;
}
1.2 ofstream对象
- ofstream对象:文件写入类
- 成员函数open()实现打开文件的操作
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ofstream out;
out.open( "test.txt" );//成员函数open()实现打开文件的操作
if( !out ){
cerr << "打开文件失败!" << endl;
return 0;
}
for ( int i=0 ; i < 10 ; i++ ){
out << i;
}
out << endl;
out.close();
return 0;
}
- open也可以接受两个参数,例如:
ifstream in( char* filename , int open_mode)
filename代表文件名,是个字符串;open_mode代表打开模式,其值用来定义以怎样的方式打开文件:
- ios::in 打开一个可读取文件;
- ios::out 打开一个可写入文件;
- ios::binary 以二进制形式(exe应用文件)打开一个文件;
- ios::app 写入的所有数据将被追加到文件末尾;
- ios::trunk 删除文件原来已存在的内容;
- ios::nocreate 若要打开的文件并不存在,那么以此参数调用open函数将无法进行;
- ios::noreplace 若要打开的文件已存在,试图用open函数打开将返回一个错误。
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ofstream out;
out.open( "test.txt" , ios::app);//追加写
if( !out ){
cerr << "打开文件失败!" << endl;
return 0;
}
for ( int i=10 ; i < 10 ; i-- ){
out << i;
}
out << endl;
out.close();
return 0;
}
两种也可以共用:
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
fstream fp( "test.txt" , ios::in | ios::out);//共用
if( !fp ){
cerr << "打开文件失败!" << endl;
return 0;
}
fp << "ilovefishc.com!";
static char str[10];
fp.seekg(ios::beg);//使得文件指针指向文件头,ios::end则是文件尾
fp >> str;
cout << str << endl;
fp.close();
return 0;
}