Hi, I have an assignment to make a program which list files and directories in the current directory (a simple version of ls). I can not finure out how to convert structures in the stat type to readable form. Here is the code:
**************************
**********
**********
******
//dirlist by Josh McCullough
//finds a dir within the current dir
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
char* getProtection(mode_t);
char* getUsername(uid_t);
char* getGroup(gid_t);
char* getDateString(time_t);
int main(int argc, char * argv[])
{
DIR *objDirPnt;
struct dirent *objDir;
struct stat objFile;
objDirPnt=opendir(get_curr
ent_dir_na
me());
printf("Mode Owner ID\tSize (b)\tModify Time\tName\n");
while((objDir=readdir(objD
irPnt))!=N
ULL)
{
stat(objDir->d_name,&objFi
le);
char *cProtection=getProtection
(objFile.s
t_mode);
char *cOwner=getUsername(objFil
e.st_uid);
char *cModifyTime=getDateString
(objFile.s
t_mtime);
printf("%s ",cProtection);
printf("%s\t",cOwner);
printf("%d\t\t",objFile.st
_size);
printf("%s\t",cModifyTime)
;
printf("%s\n",objDir->d_na
me);
}
closedir(objDirPnt);
return 0;
}
char* getProtection(mode_t vProtection)
{
char *cProtection="---------";
if(S_IRUSR & vProtection)
cProtection[0]='R';
if(S_IWUSR & vProtection)
cProtection[1]='W';
if(S_IXUSR & vProtection)
cProtection[2]='X';
return cProtection;
}
char* getUsername(uid_t vUsername)
{
return "no user";
}
char* getGroup(gid_t vGroup)
{
return "no group";
}
char* getDateString(time_t vTime)
{
struct tm *tmTime=localtime(&vTime);
static char cTime[25];
strftime(cTime,sizeof(cTim
e),"%h %e %H:%M",tmTime);
return cTime;
}
**************************
**********
**********
******
I've created a few functions, which i want to convert the info in the stat structure to readable form. For instance, getProtection should accept a mode_t type and return rwxr--r-- or something like that.
If this is unclear let me know.
Thanks,
Josh
Start Free Trial