简体   繁体   中英

Implementing ls commands in c

I am struggling with my code. I need to implement ls , ls -l , ls -i , and ls -R commands in my C program. So far I only did ls -l , ls -i , and ls -R as I am not sure how to implement ls because there is no argument. The challenge is also that after executing the program, use should be able to type % myls -l and get the results as for command ls -l .

Also right now I get Segmentation error 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);
 }
}

You are checking the contents of argv[1] and argv[2] without checking whether argv is long enough to have them. If they are not present, this results in a segfault. The length of argv is passed as argc . One simple fix for that (and to call a function for a plain ls ) would be:

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
}

Then make sure you check whether direct is NULL in your _l , _i , and _R functions before reading from it, as this will also cause a segfault. If it is NULL, you'll want to use the current directory instead.

Your SEGAFULT is caused by passing NULL to _l(direct) , _i(direct) and _R(direct) .

To fix this issue you can test if path is passed or not by changing this line from:

strcpy(direct, argv[2]);

To:

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]

Now your SEGFAULT is gone. This is assuming you don't implement the ls command yet. If you do, then you need to test argv[1] for path instead of argv[2] when there isn't -l , -i , nor -R .

It must also be noted that readdir(direct) returns a pointer to struct whose struct member name is relative to direct . This means that stat(ptr->d_name, &fst); will fail to get the stat of a path. To resolve this issue you need to change this line:

stat(ptr->d_name, &fst);

To

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

This will allow stat() to get the stat of the file's full path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM