I would like to write a simple C script in UNIX that will work like "ls -l". I have a working part where the script lists all of the files in the current directory:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
DIR *katalog;
struct dirent *dir;
katalog = opendir(".");
if (argc == 1) {
printf("without option");
if (katalog) {
while ((dir = readdir(katalog)) {
printf("%s
", dir->d_name);
}
closedir(katalog);
}
return(0);
}
}
Now I wanted to add information about the st_gid, st_uid, st_size and st_mtime. I stared from st_uid. My code looks like that now (it's compiling well under unix). Unfortunely, it gives me an error "Segmentation fault (core dumped)". I tried to look for the answer in the Stack and Internet, and I even used some hints from other threads (for example: C format issue with printf("%d", astatbuff->st_size);), but still the error occurs... I don't know what more I can change to repair it...
Here's the code that produces the error:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char *argv[])
{
DIR *katalog;
struct dirent *dir;
katalog = opendir(".");
struct stat *astat;
if (argc == 1) {
printf("Without option");
if (katalog) {
while ((dir = readdir(katalog)) != NULL && astat->st_uid != 0) {
printf("%s %llu
", dir->d_name, (unsigned long long)astat->st_uid);
}
closedir(katalog);
}
return(0);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…