在c中实现ls命令

时间:2016-04-05 20:40:27

标签: c linux shell segmentation-fault ls

我正在努力处理我的代码。我需要在C程序中实现lsls -lls -ils -R命令。到目前为止,我只执行了ls -lls -ils -R因为我不确定如何实现ls,因为没有参数。挑战还在于,在执行程序之后,使用应该能够键入% myls -l并获得与命令ls -l相同的结果。

现在我也得到了分段错误11 :(

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <grp.h>
#include <pwd.h>
#include <unistd.h>
#include <time.h>
#include <termios.h>
#include <sys/ioctl.h>

DIR * dir;
struct dirent * ptr;

int main(int argc,char *argv[])
{
// declaration for different parameters

void _l(char *direct);
void _i(char *direct);
void _R(char *direct);

// get the argc[]
char para[20];
char direct[100];
memset(direct, 0, sizeof(direct));
// copy the parameter like -l
strcpy(para, argv[1]);
// copy the path like ./
strcpy(direct, argv[2]);

// call the corresponding function according to parameters

if (strcmp(para, "-l") == 0)
{
    _l(direct);
}
if (strcmp(para, "-i") == 0)
{
    _i(direct);
}
   if (strcmp(para, "-R") == 0)
{
    _R(direct);
}


}


void _l(char *direct)
{
void mode_to_letter(int mode, char *str);
// define struct stat
struct stat fst;
struct tm * mytime = (struct tm *) malloc(sizeof(struct tm));
char str[12];
dir = opendir(direct);
// skip . and ..
readdir(dir);
readdir(dir);
while((ptr = readdir(dir)) != NULL)
{
    stat(ptr->d_name, &fst);
    // permission information
    mode_to_letter(fst.st_mode, str);
    // file type and permission
    printf("%s", str);
    // file hard links
    printf(" %d", fst.st_nlink);
    // file's owner
    printf(" %s", getpwuid(fst.st_uid)->pw_name);
    // file's owner group
    printf(" %s", getgrgid(fst.st_gid)->gr_name);
    // file size
    printf(" %ld", (long)fst.st_size);
    // file time
    mytime = localtime(&fst.st_mtime);
    printf(" %d-%02d-%02d %02d:%02d", mytime->tm_year + 1900, mytime->tm_mon + 1, mytime->tm_mday, mytime->tm_hour, mytime->tm_min);
    // file name
    printf(" %s", ptr->d_name);
    printf("\n");
  }
}

void mode_to_letter(int mode, char *str)
{
str[0] = '-';

// judge file type
if(S_ISDIR(mode)) str[0] = 'd';
if(S_ISCHR(mode)) str[0] = 'c';
if(S_ISBLK(mode)) str[0] = 'b';

// judge permission for owner
if(mode & S_IRUSR) str[1] = 'r';
else str[1] = '-';
if(mode & S_IWUSR) str[2] = 'w';
else str[2] = '-';
if(mode & S_IXUSR) str[3] = 'x';
else str[3] = '-';

// judge permission for owner group
if(mode & S_IRGRP) str[4] = 'r';
else str[4] = '-';
if(mode & S_IWGRP) str[5] = 'w';
else str[5] = '-';
if(mode & S_IXGRP) str[6] = 'x';
else str[6] = '-';

// judge permission for others
if(mode & S_IROTH) str[7] = 'r';
else str[7] = '-';
if(mode & S_IWOTH) str[8] = 'w';
else str[8] = '-';
if(mode & S_IXOTH) str[9] = 'x';
else str[9] = '-';

str[10] = '\0';
}

void _i(char *direct)
{
dir = opendir(direct);
readdir(dir);
readdir(dir);
while((ptr = readdir(dir)) != NULL)
{
    // get inode id
    printf("%ld ", (long)ptr->d_ino);
    printf("%s\n", ptr->d_name);
}
closedir(dir);
}



void _R(char *direct)
{
dir = opendir(direct);

while((ptr = readdir(dir)) != NULL)
{
    // skip . and ..
    if(!strcmp(ptr->d_name,".") || !strcmp(ptr->d_name,".."))
        continue;
    // if directory
    if (ptr->d_type & DT_DIR)
    {
        printf("%s: \n", ptr->d_name);
        // do recursively
        _R(ptr->d_name);
    }
    else
        // print the name
        printf("%s ", ptr->d_name);
 }
}

2 个答案:

答案 0 :(得分:2)

您正在检查argv[1]argv[2]的内容,而不检查argv是否足够长。如果它们不存在,则会导致段错误。 argv的长度传递为argc。一个简单的解决方法(并调用普通ls的函数)将是:

if (argc == 1) {
    _noarg(); // implement this function for a plain "ls"
} else {
    char para[20];
    char direct[100];
    memset(direct, 0, sizeof(direct));
    // copy the parameter like -l
    strcpy(para, argv[1]);
    if (argc > 2) {
        // copy the path like ./
        strcpy(direct, argv[2]);
    }
    // ... your other if statements that
    // call corresponding functions go here
}

然后确保在阅读之前检查direct_l_i函数中_R是否为NULL,因为这也会导致段错误。如果为NULL,则您将要使用当前目录。

答案 1 :(得分:0)

SEGAFULTNULL传递给_l(direct)_i(direct)_R(direct)造成的。{/ p>

要解决此问题,您可以通过更改此行来测试是否传递path

strcpy(direct, argv[2]);

要:

if(argc < 3) // checks if path is passed or not
    strcpy(direct,"."); //if path is not passed, then work on cwd
else
    strcpy(direct, argv[2]); //otherwise the path is stored in argv[2]

现在你的SEGFAULT已经消失了。这假设您尚未实现ls命令。如果您这样做,那么当没有argv[1]argv[2]-l时,您需要先测试-i代替-R

还必须注意,readdir(direct)返回指向struct的指针,该struct的结构成员名称相对于direct。这意味着stat(ptr->d_name, &fst);将无法获取路径的统计信息。要解决此问题,您需要更改此行:

stat(ptr->d_name, &fst);

char filename[127];
sprintf(filename, "%s/%s", direct, ptr->d_name);
stat(filename, &fst);

这将允许stat()获取文件完整路径的统计信息。