|
|
Posted Sep 16, 2008 at 2:50:26 PM
Subject: This programm can be run under rhel4, but can not under Fed
Hi, I am a beginner of unix system programming. So you see I have many problems in C and Unix. My programm can be run under rhel4, but can not under Fedora 8! It can show the detail of your current directory, just like "ls -l".
I kind of suspect that it is the gcc that make this happen! Bacause I cant use char* and char[] correctly.
It confuses me often.
So is anybody has some ideas about this programm or you can teach me how to use char[] and char*?
I know there are many hackers here! Thanks
//This programm is to show the datail of your local directory
#include<dirent.h>
#include<stdio.h>
#include<sys/types.h>
#include<pwd.h>
#include<sys/stat.h>
#include<grp.h>
#include<string.h>
#include<time.h>
void show_info( char *dirname );
void show_mode( int mode );
void myls3( char *dir );
int main(int argc,char *argv[])
{
if (argc < 2)
myls3(".");
else
{
while(--argc)
*++argv;
myls3(*argv); // To ls the dir you input
}
}
//open, read, and, close the directory
void myls3( char *dir )
{
DIR* dirptr;
struct dirent* info;
//open
if( NULL == (dirptr = opendir(dir)))
fprintf(stderr,"Cant open the dir %s\n",dir);
//read
while(NULL != (info = readdir(dirptr)))
show_info(info->d_name);
if(NULL == (info =(readdir(dirptr))))
fprintf(stderr,"Cant read the dir %s\n",dir);*/
closedir(dirptr);
}
//Show the details of the directory
void show_info(char *dirname)
{
struct stat* dir_rec;
if( -1 != stat( dirname,dir_rec ) )
{
show_mode(dir_rec->st_mode);
printf("%d ",dir_rec->st_nlink);
printf("%2s ",getpwuid(dir_rec->st_uid)->pw_name);
printf("%2s ",getgrgid(dir_rec->st_gid)->gr_name);
printf("%d ",dir_rec->st_size);
printf("%8s\n",ctime(&(dir_rec->st_ctime))+4);
}
}
//This fuction transfer the mode of the directory into standard form
void show_mode(int mode)
{
char *str;
strcpy(str,"----------");
if(S_ISFIFO(mode)) str[0] = '-'; //Use the macro in <sys/stat.h> to determine the permission pattern
if(S_ISDIR(mode)) str[0] = 'd';
if(S_ISCHR(mode)) str[0] = 'c';
if(S_ISBLK(mode)) str[0] = 'b';
if(S_IRUSR & mode) str[1] = 'r';
if(S_IWUSR & mode) str[2] = 'w';
if(S_IXUSR & mode) str[3] = 'x';
if(S_IRGRP & mode) str[4] = 'r';
if(S_IWGRP & mode) str[5] = 'w';
if(S_IXGRP & mode) str[6] = 'x';
if(S_IROTH & mode) str[7] = 'r';
if(S_IWOTH & mode) str[8] = 'w';
if(S_IXOTH & mode) str[9] = 'x';
printf("%s " , str);
}
|
Basile Starynkevitch
Joined Feb 04, 2009 Posts: 3
Location:near Paris (France)
Other Topics
|
Posted:
Feb 04, 2009 4:57:58 PM
Subject: This programm can be run under rhel4, but can not under Fed
char *str;
strcpy(str,"----------");
This is buggy. str should be an array of char, not a pointer. Read more about basic C programming.
It should be
char str[12]; // could be 10
strcpy(str,"---------");
--
Basile Starynkevitch http://starynkevitch.net/Basile/
|