c语言问题...想写一个简化版的ls –l 程序

来源:百度知道 编辑:UC知道 时间:2024/05/11 12:57:58
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
DIR *dir;
struct dirent *entry;
char *dirname = ".";

if (argc > 1)
dirname = argv[1];
if ((dir = opendir(dirname)) == NULL) {
perror(argv[0]);
return -1;
}

while ((entry = readdir(dir)) != NULL) {
struct stat buf;
char *type, path[MAXPATHLEN];

strcpy(path, dirname);
strcat(path, "/");
strcat(path, entry->d_name);
if (stat(path, &buf) == 0) {
switch (buf.st_mode & S_IFMT) {
case S_IFDIR: type = "[dir]"; break;
case S_IFREG: type = "[file]"; break;
default: type = "[other]

试了,编译运行一切正常,不过我是用g++编的,你也可以更新一下编译器版本试试
在你第一个程序的基础上我加了个排序,有很多地方可以优化,大致就是这个意思吧,你可以参考一下
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <dirent.h>
#include <string.h>

typedef struct mylist
{
char name[256];
char record[512];
struct mylist *next;
}MYLIST;

int main(int argc, char *argv[])
{
DIR *dir;
struct dirent *entry;
char *dirname = ".";
char tmpname[512];
MYLIST head;
MYLIST *p_tmp,*p_loop;

if (argc > 1)
dirname = argv[1];
if ((dir = opendir(dirname)) == NULL) {
perror(argv[0]);
return -1;
}

head.next = NULL;
while ((entry = readdir(dir)) != NULL) {
struct stat buf;
char *type, path[MAXPATHLEN];

strcpy(path, dirname);
strcat(path,