文档告诉俺们,wxFile是一个很小很小的类,让你在操作文件时最大程度避免负载过重(用大炮打蚊子)。事实上,由于只提供了自动出错检查及隐藏了不同平台处理文件的差异,所以它基本上没有什么负载。使用wxFile另一个开心的地方就是该类的析构函数自动关闭了它正在操作的物理文件,所以你不用时时提醒自己要记得关闭文件。
下面的例子非常简单,首先(1-18行)创建一物理文件quote.txt,然后向其内写入以下内容 :
You make me want to be a better man. 早上好!现在是北京时间10:29AM,March 16,2011年
期间分别检查了Create()函数调用后文件自动打开及Close()函数确实已把文件关闭。
第20行重新打开文件.wxFile::Read第一个参数是要打开的文件名,第二个参数是打开方式,默认是read.因为接下来的目的非常单一,要将刚刚创建的文件内容打印到控制台,所以这里用默认参数。21-22行重新检查文件是否打开以确保接下来的读操作不至失败。23行的作用是将文件指针定位到文件起始位置。为了开辟一块足够大的缓存以容纳读取的文件内容,着先调用Length()函数以获取文件长度(第24行),接着申请了一块与文件长度相同大小的缓冲content(第26行).第28-30行的while循环读取文件的内容至缓冲content中,注意在本例中不用while循环直接调用一次Read都不会有任何问题。第33行检查content里填充的数据是否即为文件quote.txt的内容。注意
cout<<wxString(content,wxConvUTF8).c_str()
它的目的是先将char*类型的字符串,转换为wxString,然后再通过标准流cout输出,这样中文内容才可以正确显示。
以下为全部代码片断,注意使用wxFile类时需添加<wx/file.h>头。
1 #include <wx/file.h>
2 void filetest()
3 {
4 wxString str(wxT("You make me want to be a better man.\r\n"));
5 str<<wxT("早上好!现在是北京时间10:29AM,March 16,2011年\r\n");
6
7 wxFile file;
8 file.Create(wxT("quote.txt"),true);
9
10 if(file.IsOpened())
11 cout<<wxString(wxT("文件已打开")).c_str()<<endl;
12
13 file.Write(str);
14 file.Close();
15
16
17
18 if(!file.IsOpened())
19 cout<<wxString(wxT("文件已关闭")).c_str()<<endl;
20
21 file.Open(wxT("quote.txt"));
22 if(file.IsOpened())
23 cout<<wxString(wxT("文件已打开")).c_str()<<endl;
24 file.Seek(0);
25 wxFileOffset filesize=file.Length();
26 cout<<"File length:"<<filesize<<endl;
27 char*content=new char(filesize);
28
29 //while(!file.Eof())
30 //{
31 file.Read((void*)content,filesize);
32 //}
33 file.Close();
34 cout<<wxString(content,wxConvUTF8).c_str()<<endl;
35
36 //将申请的资源content交回操作系统
37 delete[] content;
38 content=0;
39
40 }
2 void filetest()
3 {
4 wxString str(wxT("You make me want to be a better man.\r\n"));
5 str<<wxT("早上好!现在是北京时间10:29AM,March 16,2011年\r\n");
6
7 wxFile file;
8 file.Create(wxT("quote.txt"),true);
9
10 if(file.IsOpened())
11 cout<<wxString(wxT("文件已打开")).c_str()<<endl;
12
13 file.Write(str);
14 file.Close();
15
16
17
18 if(!file.IsOpened())
19 cout<<wxString(wxT("文件已关闭")).c_str()<<endl;
20
21 file.Open(wxT("quote.txt"));
22 if(file.IsOpened())
23 cout<<wxString(wxT("文件已打开")).c_str()<<endl;
24 file.Seek(0);
25 wxFileOffset filesize=file.Length();
26 cout<<"File length:"<<filesize<<endl;
27 char*content=new char(filesize);
28
29 //while(!file.Eof())
30 //{
31 file.Read((void*)content,filesize);
32 //}
33 file.Close();
34 cout<<wxString(content,wxConvUTF8).c_str()<<endl;
35
36 //将申请的资源content交回操作系统
37 delete[] content;
38 content=0;
39
40 }