Thursday, 7 November 2013

C Program to implement 'ls' command using directory API and various System calls.

[singh@00-13-02-56-15-7c programs]$ vi raj1.c

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

int main(void)
{
    char *curr_dir = NULL;
    DIR *dp = NULL;
    struct dirent *dptr = NULL;
    unsigned int count = 0;

    curr_dir = getenv("PWD");
    if(curr_dir == NULL)
    {
        printf("\n ERROR : Could not get the working directory\n");
        return -1;
    }

    dp = opendir((const char*)curr_dir);
    if(dp == NULL)
    {
        printf("\n ERROR : Could not open the working directory\n");
        return -1;
    }

     for(count = 0; (dptr = readdir(dp)) != NULL ; count++)
    {
        printf("%s  ",dptr->d_name);
    }
    printf("\n %u", count);
    return 0;
}








Output :

[singh@00-13-02-56-15-7c programs]$ gcc raj1.c
[singh@00-13-02-56-15-7c programs]$ ./a.out

raj11.sh  employee.txt  raj1.c~  raj14.c  raj1  raj1.sh  raj10.sh  raj6.sh  raj7.sh  raj5.sh  a.out  raj15.c  raj3.sh  raj13.c   raj8.awk  test  test4.txt  test3  raj2.sh  raj1.c  raj4.sh  raj11.sh 

No comments:

Post a Comment