C++文件操作(2)
打开文件的方式
当我们想要打开的文件不存在的时候,一般地,ofstream类的对象会默认地自动创建一个文件。而如果我们想要打开的文件是存在的,那么就会调用ofstream的构造函数或者是调用open()函数进行打开。下面,我们来看一下MSDN上面是如何定义open()函数的:
首先是函数原型:
void open( const char *_Filename, ios_base::openmode _Mode = ios_base::in | ios_base::out, int _Prot = (int)ios_base::_Openprot);void open( const char *_Filename, ios_base::openmode _Mode);void open( const wchar_t *_Filename, ios_base::openmode _Mode = ios_base::in | ios_base::out, int _Prot = (int)ios_base::_Openprot);void open( const wchar_t *_Filename, ios_base::openmode _Mode);接下来是参数的说明:
_FilenameThe name of the file to open.打开文件名_ModeOne of the enumerations in ios_base::openmode.文件的打开方式(在ios_base::openmode中定义)_ProtThe default file opening protection.默认进行文件打开时的保护OK,我们再来看看ios_base::openmode中定义的打开方式:OK,我们再来看看ios_base::openmode中定义的打开方式:
ios::in, to permit extraction from a stream.打开文件进行读操作,即读取文件中的数据ios::out, to permit insertion to a stream.打开文件进行写操作,即输出数据到文件中ios::app, to seek to the end of a stream before each insertion.打开文件之后文件指针指向文件末尾,只能在文件末尾进行数据的写入ios::ate, to seek to the end of a stream when its controlling object is first created.打开文件之后文件指针指向文件末尾,但是可以在文件的任何地方进行数据的写入ios::trunc, to delete contents of an existing file when its controlling object is created.默认的文件打开方式,若文件已经存在,则清空文件的内容ios::binary, to read a file as a binary stream, rather than as a text stream.打开文件为二进制文件,否则为文本文件
好了,open()函数的用法全部列举出来了。下面就针对ios_base::binary的二进制打开方式,我们在来谈一谈二进制文件的输出方式和文本文件的输出方式。
① 文本形式输出到文件,我们完全可以在open函数的mode选项中调用
ios::out|ios::app#include <iostream>#include<fstream>usingnamespace std;constint num=20;structpeople{ charname[num]; doubleweight; inttall; intage; charsex;};int main(){ people pe={"李勇",78.5,181,25,'f'}; ofstream fout("people.txt",ios::out|ios::app); fout<<pe.name<<" "<<pe.age<<" "<<pe.sex<<" "<<pe.tall<<" "<<pe.weight<<" "<<"\n"; fout.close(); ifstream fin("people.txt"); charch[255]; fin.getline(ch,255-1,0); cout<<ch; fin.close(); return0;}
我们可以看到,people.txt文件中的内容和命令行中的一样。
② 二进制形式输出到文件 为了能够让其用二进制方式输出文件,我们只需要把上面程序的第16行和17行换做
ofstream fout("people.txt",ios::binary);fout.write((char*)&pe,sizeofpe);#include <iostream>#include<fstream>usingnamespace std;constint num=20;structpeople{ charname[num]; doubleweight; inttall; intage; charsex;};int main(){ people pe={"李勇",78.5,181,25,'f'}; ofstream fout("people.txt",ios::binary); fout.write((char*)&pe,sizeofpe); fout.close(); people pe1={"张玲",65.4,165,62,'m'}; ifstream fin("people.txt",ios::binary); fin.read((char*)&pe1,sizeofpe1); cout<<pe1.name<<" "<<pe1.age<<" "<<pe1.sex<<" "<<pe1.tall<<" " << pe1.weight <<" "<<"\n"; fin.close(); return0;}
呼呼,以上就是我自认的自己不是很懂的C++关于如何操作文件的记录,到这里了~~全文完 ^_^