fstream、ifstream、ofstream

文件流

ofstream  //文件写操作,内存写入存储设备(文件)  输出流
通常我们所说的对一个文件进行写操作,就是把内存里的内容,也就是缓冲区的内容写到硬盘,可以将标准输出设备理解为显示器

ifstream      //文件读操作,存储设备到内存.       输入流
通常我们所说对一个文件读操作,就是把存在硬盘的内容写到内存中,也就是缓冲区

fstream      //读写操作,对打开的文件可进行读写.   前两者的结合

//文件打开方式选项
ios::in  = 0x01, //供读,文件不存在则创建(ifstream默认的打开方 式)  
ios::out  = 0x02, //供写,文件不存在则创建,若文件已存在则清空原内容(ofstream默认的打开方式)  
ios::ate  = 0x04, //文件打开时,指针在文件最后。可改变指针的位置,常和in、out联合使用  
ios::app  = 0x08, //供写,文件不存在则创建,若文件已存在则在原文件内容后写入 新的内容,指针位置总在最后  
ios::trunc = 0x10,      // 在读写前先将文件长度截断为0(默认)  
ios::nocreate  = 0x20,  //文件不存在时产生错误,常和in或app联合使用  
ios::noreplace = 0x40,   //文件存在时产生错误,常和out联合使用  
ios::binary   = 0x80  //二进制格式文件

//文件保护方式选择项
filebuf::openprot;   //默认的兼容共享方式  
filebuf::sh_none;    //独占,不共享  
filebuf::sh_read;    //读共享  
filebuf::sh_write;   //写共享

创建文件 

ofstream ofs("example.txt"); //打开文件用于写,若文件不存在就创建它  
if (!ofs) 
{
    return;//打开文件失败则结束运行  
}

ofs << setw(10) << "Name: " << "Beethoven" << endl; //使用插入运算符写文件内容   
ofs << setw(10) << "song: " << "Moonlight Sonata" << endl;
ofs.close(); //关闭文件

 fstream

open()用来打开指定的文件,可以通过is_open()判断是否打开成功
is_open();用来判断单开文件是否成功,成功返回true,发欧泽返回false
good();在没有发生任何错误的情况下返回true,否则返回false

ofstream f;
f.open("1.txt",ios_base::app);
if(!f.is_open()){
   cout<<"open error";
   return -1;
}
f<<"1234";
f<<"456";
f.close();

ifstream

open()用来打开指定的文件,可以通过is_open()判断是否打开成功
is_open();用来判断单开文件是否成功,成功返回true,发欧泽返回false
good();在没有发生任何错误的情况下返回true,否则返回false
eof();判断是否读取文件数结束,读取到结束返回true,否则返回false
fail();当读取操作类型不匹配的情况下返回true,否则返回false

int c;
ifstream inFile;
inFile.open("test.txt");//打开指定的文件
if(!inFile.is_open()){//判断打开是否成功
    cout<<"打开失败"<<endl;
}
while(inFile.good())//判断是否发生任何类型的错误
    inFile>>c;
if(inFile.eof())//判断是否文件结束
    cout<<"文件结束";
else if(inFile.fail())//是否发生类型错误,本程序c为int,当出现char类型,就会出错
    cout<<"读取失败";
else 
    cout<<"unkown error\n";
inFile.close();

getline()读取一行

ifstream fin("test.txt",ios::in);
string s;
while(getline(fin,s))
        cout << s;//输出每一行
每次从fin指向的文件中读取一行,一行之中的所有字符都会被读入,包括空格。但是结尾的空格不读入,回车换行也不读入。

打开文件的方法

调用构造函数时指定文件名和打开模式
ifstream f("d:\\12.txt", ios::nocreate); //默认以 ios::in 的方式打开文件,文件不存在时操作失败  
ofstream f("d:\\12.txt");  //默认以 ios::out的方式打开文件  
fstream f("d:\\12.dat", ios::in|ios::out|ios::binary); //以读 写方式打开二进制文件  

使用Open成员函数
fstream f;  
f.open("d:\\12.txt",ios::out);  //利用同一对象对多个文件进行操作时要用到open函数  

检查是否成功打开

成功:
if (f) {...}       //对ifstream、ofstream对象可 用,fstream对象不可用。 mysql  
if (f.good()) {...}  

失败:
if (!f) {...}       // !运算符已经重载  
if (f.fail()) {...} 

随机读写文件 

通过移动文件读写指针,可在文件指定位置进行读写。

seekg(绝对位置);      //绝对移动,    //输入流操作  
seekg(相对位置,参照位置);  //相对操作  
tellg();          //返回当前指针位置  
seekp(绝对位置);      //绝对移动,    //输出流操作  
seekp(相对位置,参照位置);  //相对操作     
tellp();          //返回当前指针位置  

参照位置: mysql
ios::beg  = 0       //相对于文件头  
ios::cur  = 1       //相对于当前位置  
ios::end  = 2       //相对于文件尾  

写文本文件的示例

fstream f("try.txt", ios::out);  
f << 1234 << ' ' << 3.14 << 'A' << "How are you"; //写入数据  
f.close();  
f.open("try.txt", ios::in);  
int i;  
double d;  
char c;  
char s[20];  
f >> i >> d >> c;  //读取数据  
f.getline(s,20);  
cout << i << endl; //显示各数据  
cout <<d << endl;  
cout << c << endl;  
cout << s << endl;  
f.close(); 

运 行结果:
1234
3.14
A
How are you
Press any key to continue

显示文本文件的内容

使用get()一次读一个字符

ifstream fin("简介.txt", ios::nocreate);  
if (!fin) 
{  
    cout << "File open error!\n";  
    return;  
}  
char c;  
while ((c=fin.get()) != EOF) cout << c; //注意结束条件的判断  
fin.close();

使用get(char *,int n,char delim='\n')一次读多个字符

ifstream fin("d:\\简介.txt",ios::nocreate);  
if(!fin)
{  
    cout<<"File open error!\n";  
    return;  
}  
char c[80];  
while(fin.get(c,80,'\0')!=NULL)cout<<c; //注意结束条件的判断  
fin.close();

使用read(char *,int n)读文件

ifstream fin("简介.txt",ios::nocreate);  
if(!fin){  
cout<<"File open error!\n";  
return;  
}  
char c[80];  
while(!fin.eof())            //判 断文件是否读结束  
{  
    fin.read(c,80);  
    cout.write(c,fin.gcount());  
}  
fin.close();

拷贝文件(二进制)

       尽管可以使用重载运算符<< 和>>,以及函数(如getline)来操作符输入和输出数据,是合法的,但是在在二进制文件中,这些操作没有什么实际意义。

       文件流包括两个为顺序读写数据特殊设计的成员函数:write 和 read。第一个函数 (write) 是ostream 的一个成员函数,都是被ofstream所继承。而read 是istream 的一个成员函数,被ifstream 所继承。类 fstream 的对象同时拥有这两个函数。它们的原型是:

write ( char* buffer, streamsize size );
read ( char* buffer, streamsize size );

buffer 是一块内存的地址,用来存储或读出数据。参数size 是一个整数值,表示要从缓存(buffer)中读出或写入的字符数。

char * buffer;  
long size;  
ifstream in (filename, ios::in|ios::binary|ios::ate);  
size = in.tellg();  
in.seekg (0, ios::beg);  
buffer = new char [size];  
in.read (buffer, size);  
in.close();  

cout << "the complete file is in a buffer";  

delete[] buffer;  
ifstream fin("1.exe", ios::nocreate|ios::binary);  
if (!fin) 
{  
    cout << "File open error!\n";  
    return;  
}  
ofstream fout("2.exe", ios::binary);  
char c[1024];  
while (!fin.eof())  
{  
    fin.read(c, 1024);  
    fout.write(c, fin.gcount());  
}  
fin.close();  
fout.close();  
cout << "Copy over!\n";


注意:若期望是二进制的文件读写,必须要指定读、写的模式有ios::binary,否则读取数据会出错。

写操作
ofstream write(char *buffer, int length) 
buffer是变量指针,一般需要强制转化成char *类型,然后加取地址符,因为任何内容都可以表现成字符的形式,而后面的length则是变量类型的字节长,一般用sizeof进行计算防止不必要的错误,下面看实例。

#include<fstream>
int main()
{
    using namespace std;
    int a = 1127;
    double b = 3.1415;
    ofstream ofs("test.txt",ios::binary);
    ofs.write((char*)&a,sizeof(int));
    ofs.write((char*)&b,sizeof(double));
}

注:(其中ios::binary以二进制方式打开文件) 

 一个打开并检查输入文件的程序

#include<iostream>  
#include<fstream>  
#include<string>  
using namespace std;  
ifstream& open_file(ifstream &in,const string &file)  
{  
    in.close();  
    in.clear();  
    in.open(file.c_str());  
    return in;  
}  
int main()  
{  
    ifstream file;  
    open_file(file,"1.txt");  
    string s;  
    while(getline(file,s))  
    {  
        cout<<s<<endl;  
    }  
    file.close();  
    return 0;  
}

(二)读操作。 
ifstream read(char * buffer, int length) 
参数和刚才一样的道理,下面看将上文的a,b输出到控制台。

#include<fstream>
int main()
{
    using namespace std;
    int a = 1127;
    double b = 3.1415;
    ofstream ofs("test.txt",ios::binary);
    ofs.write((char*)&a,sizeof(int));
    ofs.write((char*)&b,sizeof(double)); 
    ofs.close();   
    int a1;
    double b1;
    ifstream ifs("test.txt",ios::binary);
    ifs.read((char*)&a1,sizeof(int));
    cout<<a1<<endl;
    ifs.read((char*)&b1,sizeof(double));
    cout<<b1<<endl;
    ifs.close();
    return 0;
}

 其实道理很简单,应用此模式,数据类型复杂一些像结构也照样可以进行读写操作。例如。 

#include<fstream>
#include<iostream>
#include<cstring>
struct A
{
    int a;
    double b;
};
int main()
{
    using namespace std;
    A aa={1127,3.1415};
    ofstream ofs("test.txt",ios::binary);
    ofs.write((char*)&aa,sizeof(A));
    ofs.close();
    A bb;
    ifstream ifs("test.txt",ios::binary);
    ifs.read((char*)&bb,sizeof(A));
    cout<<bb.a<<endl;
    cout<<bb.b<<endl;
    return 0;
}

参考:

http://www.it610.com/article/5040888.htm

发布了142 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_30460949/article/details/100079120