次のように:例は、C言語、Cライブラリを使用して、ファイルシステムのディレクトリの内容を確認します。
書式#include <stdio.hに>
書式#include <dirent.h>
INTメイン(INTのargc、char型のconst * ARGV [])
{
DIR * DP =のopendir( "");
構造体* dは言いました。
一方、(D = READDIR(DP))
printf( "%sの\ n" は、D-> d_name)。
closedirの(DP)。
0を返します。
}
このコードの利点と欠点はそれがポインタです。コードはシンプルかつエレガントな、読み込むのに適していますが、セキュリティ上のリスクがあります。ヌルポインタをどのように扱いますか?ライブラリは解放するメモリブロック(へのポインタ)を割り当てましたか?
書式#include <iostreamの>
書式#include <dirent.h>
名前空間stdを使用。
クラスDir_offset {
フレンドクラスのDir。
民間:
長いリットル;
Dir_offset(長いN){L = N。}
長いtell_dir(){戻りL。}
}。
クラスます{
公:
ディレクトリ(定数のchar *);
〜のDir();
int型の読み取り(のdirent&);
ボイド(Dir_offset)求めます。
()constとして伝えDir_offset。
民間:
DIR * DP;
あなた(のconst&あなた)。
あなた&演算子=(定数&あなた)。
}。
DIR :: DIR(CONST文字*ファイル):DP(opendirなど(ファイル)){}
Dir ::〜のDir(){
(DP)の場合
closedirの(DP)。
}
void Dir::seek(Dir_offset pos){
long l = pos.tell_dir();
if(dp)
seekdir(dp, l);
}
Dir_offset Dir::tell() const{
if(dp)
return telldir(dp);
return -1;
}
int Dir::read(dirent& d){
if(dp){
dirent* r = readdir(dp);
if(r){
d = *r;
return 1;
}
}
throw("dirent isn't exist.\n");
return 0;
}
int main(int argc, char const *argv[])
{
Dir dp("C:\\");
dirent d;
try{
while(dp.read(d))
cout << d.d_name <<endl;
}catch (const char* msg){
cerr << msg << endl;
}
return 0;
}
此段代码main函数同样简洁优美,适合阅读。更重要的是接口设计被优化了。
Dir dp("C:\\"); ---- 对象被创建,但是DIR* dp是对象的私有数据,被隐藏管理了,无法直接访问,这就是C++对指针的管理。
~Dir() 对分配的内存做了释放管理。类消亡了,内存自动释放。
所有指针管理的问题做了处理,对外的接口是类以及其成员函数。