|
/*读取指定目录下的文件,这段代码读取/目录下的文件*/
#include <iostream>
using namespace std;
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <time.h>
int main(int argc, char* argv[])
{
DIR *dp;
struct dirent *dirp;
if (argc == 1)
dp = opendir( "/" );
else
dp = opendir( argv[1] );
while ( (dirp = readdir(dp)) != NULL) {
struct stat st;
char fn[200];
if (argc == 1)
strcpy(fn, dirp->d_name);
else
sprintf(fn, "%s//%s", argv[1], dirp->d_name);
if( stat(fn, &st) < 0) {
cout << "error" << endl;
continue;
}
if S_ISREG(st.st_mode) {
cout << "-";
}else if S_ISDIR(st.st_mode) {
cout << "D";
}else if S_ISCHR(st.st_mode) {
cout << "C";
}else if S_ISBLK(st.st_mode) {
cout << "B";
}else if S_ISFIFO(st.st_mode) {
cout << " ";
}else if S_ISLNK(st.st_mode) {
cout << "L";
}else if S_ISSOCK(st.st_mode) {
cout << "S";
} else
cout << "?";
if (st.st_mode & S_IRUSR)
cout << "r";
else
cout << "-";
if (st.st_mode & S_IWUSR)
cout << "w";
else
cout << "-";
if (st.st_mode & S_IXUSR)
cout << "x";
else
cout << "-";
if (st.st_mode & S_IRGRP)
cout << "r";
else
cout << "-";
if (st.st_mode & S_IWGRP)
cout << "w";
else
cout << "-";
if (st.st_mode & S_IXGRP)
cout << "x";
else
cout << "-";
if (st.st_mode & S_IROTH)
cout << "r";
else
cout << "-";
if (st.st_mode & S_IWOTH)
cout << "w";
else
cout << "-";
if (st.st_mode & S_IXOTH)
cout << "x";
else
cout << "-";
cout << " " << ctime( &st.st_mtime ) << " ";
cout << " " << st.st_mtime;
cout << " " << st.st_uid << ":" << st.st_gid;
cout << " ";
cout.width(;
cout << st.st_size;
cout << " " << dirp->d_name << endl;
}
closedir(dp);
}
运行结果是:
Drwx------ Sat Apr 17 21:39:15 2004
1082209155 500:500 376 .
Drwxr-xr-x Wed Apr 14 21:13:15 2004
1081948395 0:0 72 ..
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
error
这是怎么一回事阿?该怎么写才可以显示非"."目录下的文件?
如果把"/"改成"."就没有问题了. |
|