System commands from c
Fernando RUIZ CASAS
correo at fernando-ruiz.com
Tue May 11 07:15:23 UTC 2004
On Mon, 10 May 2004 15:27:14 -0600, Steve Holle wrote:
>
> I there any way to issue a file system command from within c, such as 'ls'?
Hi,
at
http://www.rtems.com/cgi-bin/cvsweb.cgi/rtems/cpukit/libmisc/shell/cmds.c?rev=1.17&content-type=text/x-cvsweb-markup
you can see this & more ready to use.
int main_ls(int argc, char *argv[])
{
char * fname;
DIR *dirp;
struct dirent *dp;
struct stat stat_buf;
struct passwd * pwd;
struct group * grp;
char * user;
char * group;
char sbuf[256];
char nbuf[1024];
int n,size;
fname=".";
if (argc>1) fname=argv[1];
if ((dirp = opendir(fname)) == NULL)
{
fprintf(stdout,"%s: No such file or directory.\n", fname);
return errno;
}
n=0;
size=0;
while ((dp = readdir(dirp)) != NULL)
{
strcpy(nbuf,fname);
if (nbuf[strlen(nbuf)-1]!='/') strcat(nbuf,"/");
strcat(nbuf,dp->d_name); /* always the fullpathname. Avoid ftpd problem.*/
if (stat(nbuf, &stat_buf) == 0)
{ /* AWFUL buts works...*/
strftime(sbuf,sizeof(sbuf)-1,"%b %d %H:%M",gmtime(&stat_buf.st_mtime));
pwd=getpwuid(stat_buf.st_uid);
user=pwd?pwd->pw_name:"nouser";
grp=getgrgid(stat_buf.st_gid);
group=grp?grp->gr_name:"nogrp";
fprintf(stdout,"%c%c%c%c%c%c%c%c%c%c %3d %6.6s %6.6s %11d %s %s%c\n",
(S_ISLNK(stat_buf.st_mode)?('l'):
(S_ISDIR(stat_buf.st_mode)?('d'):('-'))),
(stat_buf.st_mode & S_IRUSR)?('r'):('-'),
(stat_buf.st_mode & S_IWUSR)?('w'):('-'),
(stat_buf.st_mode & S_IXUSR)?('x'):('-'),
(stat_buf.st_mode & S_IRGRP)?('r'):('-'),
(stat_buf.st_mode & S_IWGRP)?('w'):('-'),
(stat_buf.st_mode & S_IXGRP)?('x'):('-'),
(stat_buf.st_mode & S_IROTH)?('r'):('-'),
(stat_buf.st_mode & S_IWOTH)?('w'):('-'),
(stat_buf.st_mode & S_IXOTH)?('x'):('-'),
(int)stat_buf.st_nlink,
user,group,
(int)stat_buf.st_size,
sbuf,
dp->d_name,
S_ISDIR(stat_buf.st_mode)?'/':' ');
n++;
size+=stat_buf.st_size;
}
}
fprintf(stdout,"%d files %d bytes occupied\n",n,size);
closedir(dirp);
return 0;
}
More information about the users
mailing list