LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 544|回复: 3

运行这段程序为什么总是有error?请高人指点: 谢谢

[复制链接]
发表于 2004-4-16 08:56:26 | 显示全部楼层 |阅读模式
/*读取指定目录下的文件,这段代码读取/目录下的文件*/
#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

这是怎么一回事阿?该怎么写才可以显示非"."目录下的文件?
如果把"/"改成"."就没有问题了.
发表于 2004-4-16 11:02:22 | 显示全部楼层
你的东西看起来真的是有难度啊……
发表于 2004-4-16 19:55:29 | 显示全部楼层
最好别把C和C++混合在一使用。
以后贴代码最好用code功能整理一下。不然太不好看。
发表于 2004-4-17 00:22:47 | 显示全部楼层

strcpy(fn, dirp->d_name);
改成
sprintf(fn, "/%s", dirp->d_name);
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表