I'm trying to create a program that functions similarly to the default ls
command using C. I'm having some troubles with one of the attributes ( -l
) and the formatting currently. For the -l
, it is not running the line that is supposed to make it a simple list with the inodes and names (argv[2]) and instead functions the same as -f
.
#include <stdio.h>
#include <sys/types.h>
#include <sys/dir.h>
#include <sys/stat.h>
struct direct **dirs;
int main (int argc, char* argv[])
{
struct stat statb;
int nent, i;
int x = 0;
int y;
char *F = argv[1];
char *l = argv[2];
char *others = argv[3];
nent = scandir (".", &dirs, NULL, NULL);
for (i = 0; i < nent; i ++) {
if(argv[1]) {
stat(dirs[i]->d_name, &statb);
if (y == 0) {
printf("\n%-16s",dirs[i]->d_name);
switch (statb.st_mode & S_IFMT) {
case S_IFDIR :
printf("/\t ");
break;
case S_IFREG :
printf("*\t ");
break;
}
}
else {
printf ("%-16s",dirs[i]->d_name);
switch (statb.st_mode & S_IFMT) {
case S_IFDIR :
printf("/\t ");
break;
case S_IFREG :
printf("*\t ");
break;
}
}
x++;
y = x%5;
}
else if (argv[2]) {
printf("I-node = %d name = %s\n", dirs[i]->d_ino, dirs[i]->d_name);
}
else {
if (y == 0) {
printf("\n%-16s\t ",dirs[i]->d_name);
}
else {
printf("%-16s\t ",dirs[i]->d_name);
}
x++;
y = x%5;
}
}
printf("\n");
}
You will never enter the else
clause. If argv[1]
is NULL, then argv[2]
will be NULL. You just need to parse the arguments.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.