阿那達在寫IR作業時需要開大量的檔案,她發現最多開檔量為509個,於是我也用自己的電腦來跑一下,當然結果一模一樣。
我想這跟作業系統的設定有關,記得在作業系統課,老師有在系上Linux主機跑File Descriptor有多少個,結果跑了1024個出來,比在Windows XP還要多。
在Windows上有誰寫程式需要開啟大量檔案呢?一般人可不會處理太多檔案,就算處理成千上萬個檔案,只要適時地加上關檔的動作,即可解決最大開檔數的問題!
先來看一下程式碼:
/**
Theme: Max Number of File Descriptor
Compiler: Dev C++ 4.9.9.2
Date: 100/04/18
Author: ShengWen
Blog: https://cg2010studio.wordpress.com/
*/
#include<iostream>
#include<fstream>
using namespace std;
const int N=1000;
const int n=10;
int main(){
fstream fout[N];
char line[N];
char numberx[n];
int out;
for(int i=0; i<N; i++){
itoa(i, numberx, 10);
//將i整數以10為基底轉為numberx字元指標
strcat(numberx, ".txt");
//將numberx接上.txt字串
fout[i].open(numberx, ios::out);
if(fout[i]==0)//當指標指向0(為空)
system("pause");
cout<<i<<':'<<fout[i]<<endl;
//fout[i].close();
}
system("pause");
return EXIT_SUCCESS;
}
跑出部份結果為:
499:0x220ad8
500:0x220bd8
501:0x220cd8
502:0x220dd8
503:0x220ed8
504:0x220fd8
505:0x2210d8
506:0x2211d8
507:0x2212d8
508:0x2213d8
請按任意鍵繼續 . . .
509:0
請按任意鍵繼續 . . .
可以看到,若我不關閉檔案指標,指標的位址會不斷地改變,直到所有FD被用光,之後(509號)的檔案指標無法取得File Descriptor,便指向「空」。
若我把fout[i].close();的註解拿掉,每一回合開檔後即關檔,結果會是:
988:0x23f3d8
989:0x23f4d8
990:0x23f5d8
991:0x23f6d8
992:0x23f7d8
993:0x23f8d8
994:0x23f9d8
995:0x23fad8
996:0x23fbd8
997:0x23fcd8
998:0x23fdd8
999:0x23fed8
請按任意鍵繼續 . . .
可以發現,檔案指標位址依然會不斷更改,但是因為File Descriptor一直有空位(其實每回合只有一個FD),因此可以持續開啟檔案,相當有趣呢!
另外可以觀察到,fstream型態的變數佔了256 bytes(2^8 bytes),因為要記載檔案標頭及相關資訊,int型態的變數也才4 bytes,看來檔案標頭記載相當多的資訊呢!可以參考MS的說明FILEDESCRIPTOR Structure。
typedef struct _FILEDESCRIPTOR {
DWORD dwFlags;
CLSID clsid;
SIZEL sizel;
POINTL pointl;
DWORD dwFileAttributes;
FILETIME ftCreationTime;
FILETIME ftLastAccessTime;
FILETIME ftLastWriteTime;
DWORD nFileSizeHigh;
DWORD nFileSizeLow;
TCHAR cFileName[MAX_PATH];
} FILEDESCRIPTOR, *LPFILEDESCRIPTOR;
突然想到,我們還要考慮3個標準FD,也就是:
| Integer value | Name |
|---|---|
| 0 | Standard Input (stdin) |
| 1 | Standard Output (stdout) |
| 2 | Standard Error (stderr) |
所以Windows總共有512個FD,恰好是Linux的一半呢!
The file descriptors for input, output, and error.
參考維基百科:File Descriptor。
隨意留個言吧:)~