簡體   English   中英

解決在C中實現類似LS命令的功能的代碼

[英]Troubleshoot code implementing LS command like functionalities in C

我已經草擬了一個代碼片段,以在名為My $ HELL的自定義外殼中模擬ls -all的操作。主外殼進程調用此代碼(通過execlp調用其可執行文件)。

以下是可執行工作的可執行文件myls的代碼:-

myls.c

#include <stdio.h>     
#include <stdlib.h>    
#include <sys/types.h>  
#include <dirent.h>    
#include <sys/stat.h> 
#include <time.h>


void search_dir(const char * arg); 

void main(int argc, char *argv[])
{
    int i;  
    if (argc==1)
        search_dir(".");
    for(i=1;i<argc;i++)
        search_dir(argv[i]);
}

 void search_dir(const char *arg)//Function to read directories and file attributes//
{
    DIR *dirp;
    struct dirent *dp;//Dirent structure used to read and store directory attributes//
    char file_name[256];
    char time[50]={"\0"};
    struct tm *timeinfo;
    struct stat prop_file;//stat function for accessing file attributes//
    char type;

    if((dirp=opendir(arg))==NULL)
    {
        perror("opendir");
        return;
    }

    printf("\n\nDirectory \tTime last Modified\tSize\t\t  Name\n");
    while((dp=readdir(dirp))!=NULL) // Navigates the directory structure
    {

        if ( stat(dp->d_name,&prop_file)!=0) //Reading file attributes//
        {
            printf("\n%s:Error in reading the file attributes", dp->d_name );   
            continue;
        }
        if ( dp->d_type==8 )
        {
            type = '-';
        }
        else
        {
            type = 'd';
        }
        timeinfo=localtime(&(prop_file.st_mtime));
        strftime(time,20,"%b %d %H:%M", timeinfo);
        printf("\n %c\t\t %s\t\t%d\t\t %s",type,time,(int)prop_file.st_size,dp->d_name); //Printing ile attributes//
    }
    printf("\n");
}

無論目錄中的內容如何,​​該過程都會顯示某些字段,在此之后,調用過程會因分段錯誤而終止。

GDB運行也有一點幫助(因為含糊不清),對錯誤的搜索幾乎沒有結果。 以下是調試的輸出:

[~pbox/working/trial]<My$HELL>myls
Executing myls


Directory   Time last Modified  Size          Name

 d       Aug 14 19:22       4096         ..
 d       Aug 14 18:42       4096         .
[~pbox/working/trial]<My$HELL>

Program received signal SIGSEGV, Segmentation fault.
strlen () at ../sysdeps/x86_64/strlen.S:106
106 ../sysdeps/x86_64/strlen.S: No such file or directory.
(gdb) Quit

據我了解,這種錯誤是非法變量/指針分配的結果。 非常感謝您指出此錯誤。

我還會在調用myls的地方附加主進程的代碼段

main.c

.
.
    else if(strcmp(command[0],"myls")==0)   //command of type char ** stores the user input command check if the first field is 'myls'//        
                {
                    printf("Executing myls\n");
                    strcat(path,"/myls"); //path stores the directory path
                    result=execvp(path,command); //result of type int
                    exit(0);
                }   
.
.

歡呼和感謝!

以下代碼:

1) cleanly compiles
2) handles errors in an appropriate manner
3) does the job correctly
4) does not follow symbolic links
5) does not display the proper file type for every file
6) when accessing directories that are (in any way) protected
   from casual reading, will output an error message
7) properly builds the path+filename before calling stat()
8) properly declares main() function and proper return
9) does not handle any options that are passed in.
10)does not seg fault



#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <time.h>
#include <string.h>


void search_dir(const char * arg);

int main(int argc, char *argv[])
{
    int    i;
    char   dirBuf[128] = {'\0'};
    char * newline = NULL;

    if (argc==1)
        search_dir(".");
    else
    {
        for(i=1;i<argc;i++)
        {
            newline = strcpy( dirBuf, argv[i] );
            if( strstr( dirBuf, "\n") )
            {
                 *newline = '\0';
            }
            search_dir(dirBuf);
        }
    }
    return 0;
}

 void search_dir(const char *arg)//Function to read directories and file attributes//
{
    DIR *dirp;
    struct dirent *dp;//Dirent structure used to read and store directory attributes//
    char fileName[256];
    char fileTime[50]={"\0"};
    struct tm *timeinfo;
    struct stat prop_file;//stat function for accessing file attributes//
    char type;

    printf( "%s\n", arg);

    if( NULL == (dirp=opendir(arg)) )
    {
        perror("opendir failed");
        return;
    }

    // implied else, opendir successful

    printf("\n\nDirectory \tTime last Modified\tSize\t\t  Name\n");

    while( NULL != (dp=readdir(dirp)) ) // gets next entry in current directory,
    {
        strcpy(fileName, arg);
        strcat(fileName, "/");
        strcat(fileName, dp->d_name);
        printf( "\nfileName: %s", fileName);

        if ( stat(fileName,&prop_file) ) //Reading file attributes//
        {
            perror( "stat failed" );
            printf("\n%s:Error in reading the file attributes", dp->d_name );
            continue;
        }

#ifdef _DIRENT_HAVE_D_OFF
        // following if/else needs expansion
        if ( dp->d_type==8 )
        {
            type = '-';
        }

        else
        {
            type = 'd';
        }
#else
        type = '?';
#endif

        timeinfo=localtime(&(prop_file.st_mtime));
        strftime(fileTime, 49, "%b %d %H:%M", timeinfo);
        printf("\n %c\t\t %s\t\t%d\t\t %s",
            type,
            fileTime,
            (int)prop_file.st_size,
            dp->d_name); //Printing file attributes//
    }
    printf("\n");
    closedir( dirp );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM