11. 文字檔與二進位檔
文字檔 |
二進位檔 |
|
資料可讀性 |
容易 |
困難 |
輸入/輸出效率 |
差 |
佳 |
檔案空間大小 |
通常較大 |
通常較小 |
檔案可攜帶性 |
通行 |
差 |
浮點數存取誤差 |
有 |
無 |
12. istream::read
讀取物件.read(資料區塊的指標, 長度);
例:
ifstream InFoo("data.dat", ios::in | ios::binary);
int buffer;
InFoo.read( reinterpret_cast<char*>(&buffer), sizeof(int) ); // 讀取資料,reinterpret_cast<T>(S)後面介紹
InFoo.close();
同樣的,可以一次讀取整個 結構(struct) 或 類別(class)
例:
struct aa
{
int i;
char c[24];
DWORD d;
};
aa* bb = new aa;
InFoo.read( reinterpret_cast<char*>(bb), sizeof(aa) );
13. ostream::write
輸出物件.write(資料區塊的指標, 長度);
例:
// 複製檔案
#include <fstream>
using namespace std;
int main () {
char * buffer;
long size;
ifstream infile ("test.txt",ifstream::binary);
ofstream outfile ("new.txt",ofstream::binary);
// 取得檔案大小
infile.seekg(0,ifstream::end);
size=infile.tellg();
infile.seekg(0);
// 挖一塊與檔案大小相同的記憶體
buffer = new char [size];
// 讀取資料
infile.read (buffer,size);
// 輸出資料
outfile.write (buffer,size);
// 釋放記憶體
delete[] buffer;
outfile.close();
infile.close();
return 0;
}
14. 讀寫位置
在C++ I/O系統掌管兩個與檔案相關的指標,
一個是讀取指標,一個則是輸出指標,都是在表示目前讀寫的位置。
接著介紹如何控制這些指標。
15. istream::seekg && ostream::seekp
這兩個分別用於輸出輸入,方式一樣
讀取物件.seekg(相對位置, 基準值);
輸出物件.seekp(相對位置, 基準值);
基準值在 iostream.h 定義:
ios::beg // 檔案開頭
ios::cur // 目前位置
ios::end // 檔案結尾
例:
file1.seekg(1234,ios::cur); // 把檔案讀取指標從目前位置向後移1234個字元
file2.seekp(1234,ios::beg); // 把檔案的輸出指標從開頭向後移1234個字元
例:
// 讀取檔案到記憶體
#include <iostream>
#include <fstream>
using namespace std;
int main () {
int length;
char * buffer;
ifstream is;
is.open ("test.txt", ios::binary );
// 取得檔案大小
is.seekg (0, ios::end);
length = is.tellg();
is.seekg (0, ios::beg);
// 挖記憶體
buffer = new char [length];
// 讀取資料
is.read (buffer,length);
is.close();
cout.write (buffer,length);
return 0;
}
16. istream::tellg && ostream::tellp
讀取物件.tellg();
輸出物件.tellp();
這兩個一樣分別用於輸入輸出,用來取得目前指標的位置。
例:
#include <fstream.h>
void main()
{
// 假如我们已经在test_file.txt中存有了“Hello”的内容
ifstream File("test_file.txt");
char arr[10];
File.read(arr,10);
// 由于Hello占5个字符,因此这里将返回5
cout << File.tellg() << endl;
File.close();
}
17. istream::ignore
讀取物件.ignore(長度, 條件);
和 seekg 很類似,但是 ignore 可以限定條件讓動作停下
例:
#include <fstream.h>
void main()
{
// 假设t
est_file.txt中已经存有"Hello World"这一内容
ifstream File("test_file.txt");
static char arr[10];
// 假如一直没有遇到字符"l",则向前定位直到跳过6个字符
// 而如果期间遇到"l",则停止向前,定位在该处
File.ignore(6,’l’);
File.read(arr,10);
cout << arr << endl; // 它将显示"lo World!"
File.close();
}
18. reinterpret_cast<T>(S)
static_cast<Type> 可以轉換變數的靜態型態,跟舊式C的強制轉型蠻類似的.
dynamic_cast<Type> 可以把指向base class object的指標或reference轉換成指向derived class的指標或reference, 當指到的物件真的是derived class object.
const_cast<Type> 可以改變某物的常數性或是變易性.
reinterpret_cast<Type> 大多是用在轉換函式指標型別的.
從http://www.cis.nctu.edu.tw/~is92004/article/cast轉來的@@~
簡單來說,就是把S的型別看作T。
◎參考:
http://blog.donews.com/sunnny/
http://www.cplusplus.com/
PPT01
PPT02
其實還有一些沒介紹到,但是我自己也沒過,就不多說啦
話說這裡的編輯器我還真不熟