UNIX环境高级编程学习之第四章文件和目录-用C实现Shell中的”ls -l”功能
[code lang=”cpp”]// 只能查看目录中的所有文件属性
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
int main(int argc, char *argv[])
{
char szDirPath[512] = { 0 };
char szFilePath[512] = { 0 };
DIR * pDIR;
if (argc > 1)
{
strcpy(szDirPath, argv[1]);
}else {
strcpy(szDirPath, ".");
}
pDIR = opendir(szDirPath);
if (NULL == pDIR)
{
printf("Open DIR[%s] Error! /n", szDirPath);
return -1;
}
struct dirent* pdirent;
int n = 0;
int i;
int y;
char szName[256];
char szLineData[512];
struct stat file_stat;
while ( (pdirent = readdir(pDIR)) != NULL)
{
memset(szName, 0, sizeof(szName));
memset(szLineData, 0, sizeof(szLineData));
memset(szFilePath, 0, sizeof(szFilePath));
memset(&file_stat, ‘/0’, sizeof(file_stat));
strcpy(szName, pdirent->d_name);
sprintf(szFilePath, "%s/%s", szDirPath, szName);
stat(szFilePath, &file_stat);
time_t t = file_stat.st_mtime;
int len = strlen(szName);
if (pdirent->d_type == DT_DIR) // 文件夹
{
szName[len] = ‘//’;
}else if (pdirent->d_type == DT_DIR) // 符号连接
{
szName[len] = ‘@’;
}
sprintf(szLineData, "%-32s uid=%-8u gid=%-8u LastDate=%s ", szName, file_stat.st_uid, file_stat.st_gid, ctime(&t));
printf(szLineData);
}
printf("/n");
closedir(pDIR);
return 0;
}

[/code]

发表评论