详解C++文件读写操作
在看C++编程思想中,每个练习基本都是使用ofstream,ifstream,fstream,以前粗略知道其用法和含义,在看了几位大牛的博文后,进行整理和总结: 这里主要是讨论fstream的内容: #include <fstream> ofstream //文件写操作 内存写入存储设备 ifstream //文件读操作,存储设备读区到内存中 fstream //读写操作,对打开的文件可进行读写操作 1.打开文件 <span style="font-family:Times New Roman;font-size:16px;"> public member function void open ( const char * filename,ios_base::openmode mode = ios_base::in | ios_base::out ); void open(const wchar_t *_Filename,ios_base::openmode mode= ios_base::in | ios_base::out,int prot = ios_base::_Openprot); </span> 参数: filename 操作文件名 这些方式是能够进行组合使用的,以“或”运算(“|”)的方式:例如 ofstream out; out.open("Hello.txt",ios::in|ios::out|ios::binary) //根据自己需要进行适当的选取 打开文件的属性同样在ios类中也有定义:
对于文件的属性也可以使用“或”运算和“+”进行组合使用,这里就不做说明了。 <span style="font-family:Times New Roman;font-size:16px;"> ofstream out("...",ios::out); ifstream in("...",ios::in); fstream foi("...",ios::in|ios::out); </span> 当使用默认方式进行对文件的操作时,你可以使用成员函数is_open()对文件是否打开进行验证 3.文本文件的读写 // writing on a text file #include <fiostream.h> int main () { ofstream out("out.txt"); if (out.is_open()) { out << "This is a line.n"; out << "This is another line.n"; out.close(); } return 0; } //结果: 在out.txt中写入: This is a line. This is another line 从文件中读入数据也可以用与 cin>>的使用同样的方法: // reading a text file #include <iostream.h> #include <fstream.h> #include <stdlib.h> int main () { char buffer[256]; ifstream in("test.txt"); if (! in.is_open()) { cout << "Error opening file"; exit (1); } while (!in.eof() ) { in.getline (buffer,100); cout << buffer << endl; } return 0; } //结果 在屏幕上输出 This is a line. This is another line 上面的例子读入一个文本文件的内容,然后将它打印到屏幕上。注意我们使用了一个新的成员函数叫做eof ,它是ifstream 从类 ios 中继承过来的,当到达文件末尾时返回true 。 获得和设置流指针(get and put stream pointers)
我们可以通过使用以下成员函数来读出或配置这些指向流中读写位置的流指针: 流指针 get 和 put 的值对文本文件(text file)和二进制文件(binary file)的计算方法都是不同的,因为文本模式的文件中某些特殊字符可能被修改。由于这个原因,建议对以文本文件模式打开的文件总是使用seekg 和 seekp的第一种原型,而且不要对tellg 或 tellp 的返回值进行修改。对二进制文件,你可以任意使用这些函数,应该不会有任何意外的行为产生。 // obtaining file size #include <iostream.h> #include <fstream.h> const char * filename = "test.txt"; int main () { long l,m; ifstream in(filename,ios::in|ios::binary); l = in.tellg(); in.seekg (0,ios::end); m = in.tellg(); in.close(); cout << "size of " << filename; cout << " is " << (m-l) << " bytes.n"; return 0; } //结果: size of example.txt is 40 bytes. 4.二进制文件 // reading binary file #include <iostream> #include <fstream.h> const char * filename = "test.txt"; int main () { 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; return 0; } //运行结果: The complete file is in a buffer 5.缓存和同步(Buffers and Synchronization)
以上就是本文的全部内容,希望对大家的学习有所帮助。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |