最近在学C++,做点小功课,记录下。
(1)为要进行操作的文件定义一个流。 (2)建立(或打开)文件。如果文件不存在,则建立该文件;如果磁盘上已存在该文件,则打开它。 (3)进行读/写操作。在建立(或打开)的文件上执行所要求的输入/输出操作。一般来说,在主存与外设的数据传输中,由主存到外设叫做输出或写,而由外设到主存叫做输入或读。 (4)关闭文件。
贴的代码使用时需添加头文件
#include "fstream" #include <iostream>运行程序后,我们就会在程序的相应的目录下发现一个ofstream.txt文件,打开之后会显示“Hello,Bobo!”。
注意:在完成对整个文件的操作之后,一定要用close()函数将文件关闭,否则在程序结束后,所操作的文件将不会保存!
如果直接使用 fin>>char[]读取文件时,有一个问题,就是插入符>>遇到空字符便会停止输出。这里的空字符就是空格,或者是’\0’。如果我们在文件中有空格字符,那么空格后面的字符就无法被输出到屏幕上了。因此使用了getline()函数。
如何停止用户输入呢?在我们输入完一段话之后,肯定会按下回车。之后我们向该函数发出EOF标志,即文件结束符标志(End Of File)。在命令行里面发送文件结束符的方法是“Ctrl+Z”,之后再次按下回车键就能停止输入了。
可以调用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 );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. 打开文件为二进制文件,否则为文本文件使用示例: (1)ios::out|ios::app
#include <iostream> #include<fstream> using namespace std; const int NAME_SIZE=20; struct people { char name[NAME_SIZE]; int age; char sex; }; int main() { people sb ={"张三",25,'m'}; ofstream fout("people.txt",ios::out|ios::app); fout<<sb.name<<" "<<sb.age<<" "<<sb.sex<<"\n"; fout.close(); ifstream fcin("people.txt"); char temp[255]; fcin.getline(temp,255-1,0); cout<<temp; fcin.close(); return 0; }说明:文本形式输出到文件,app(append)模式,表示以追加的方式写入文件,即添加到文件末尾。 (2)ios::binary
#include <iostream> #include<fstream> using namespace std; const int NAME_SIZE = 20; struct people { char name[NAME_SIZE]; int age; char sex; }; int main() { people pe={"张三",25,'f'}; ofstream fout("people.txt",ios::binary); fout.write((char*)&pe,sizeof pe); fout.close(); people pe1={"张玲",62,'m'}; ifstream fin("people.txt",ios::binary); fin.read((char*)&pe1,sizeof pe1); cout<<pe1.name<<" "<<pe1.age<<" "<<pe1.sex<<"\n"; fin.close(); return 0; }说明:二进制形式,在写时需要调用write函数。该函数有两个参数,第一个是要写入数据的首地址,第二个参数是要写入的字符数目。
