Search code examples
creaddir

retrieving attributes of files from a folder


I am doing an assignment that requires me to create a function similar to ls. My code works fine but when it comes to implementing the behaviour of

ls -l child //where child is a folder

there is a weird behaviour.

Let's say i am in the folder 'parent' and in it i have a subfolder, 'child' which contains some text files. When i run my program from the parent folder, it finds the folder and prints out the attributes of the text files in it. However, it will only print the files in the child folder only if the same files itself exists in the parent folder.

Here is a snippet of the code that i am using,

    char CurrDir[100];
    DIR *pDir = NULL;
    struct dirent *pFileNames = NULL;

    getcwd(CurrDir, sizeof(CurrDir))

    strncat(CurrDir, "/", strlen(CurrDir));

    unsigned int CurrDirLen = strlen(CurrDir);
    unsigned int CombSize = CurrDirLen + strlen(argv[1]);

    char SuperCharArr[CombSize];

    for(int i = 0; i < CombSize; ++i)
    {
        if( i < strlen(CurrDir) )
            SuperCharArr[i] = CurrDir[i];
        else
            SuperCharArr[i] = argv[1][i%CurrDirLen];
    }//for

    //insert null character at the end of the character
    SuperCharArr[CombSize] = '\0';

    pDir = opendir( SuperCharArr );
    printf("%s\n", SuperCharArr);

    if( pDir != NULL )
    {
        //Directory detected as pDir is a DirectoryStream
        printf("%s\n", "pDir not null");
        PrintHeader();

        while( (pFileNames = readdir(pDir)) != NULL )
        {
            PrintFileDeails(pFileNames);
        }
    }//if

Solution

  • In my original code posted here, there was a function called, PrintFileDeails(pFileNames), which takes in a parameter of type direct.

    Within PrintFileDeails(), there is a function that checks on the status of the file and the code is as follows,

    struct stat FileStat;
    
    if( stat(pFileNames->d_name, &FileStat) == -1 )
    {
        perror("stat");
        exit(EXIT_FAILURE);
    }//if
    

    This line of code would print out an error where they couldn't find the file and with AAT's comment made me go thru my code again as i suspect that it was not reading the correct folder. Hence, after i passed the full path of where it is supposed to read the file from and it worked fine. Hence, the code was changed to this instead.

    if( stat(pFullPath, &FileStat) == -1 )
    {
        perror("stat");
        exit(EXIT_FAILURE);
    }//if
    

    where pFullPath was passed the variable of SuperCharArr which contained the full path of where the file to be searched was.

    The man page for stat() helped too and it can be found here