Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
208 views
Welcome To Ask or Share your Answers For Others

1 Answer

As astat is not yet initialize/assign before astat->st_uid, code exhibir undeifed behavior (UB). In OP case, the code crashed,

Instead of declaring a pointer with no value, code nneds to:

1) Declare a struct stat object.

2) Populated it with a *stat() call. ref.

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) {
        // add
        struct stat sb;
        if (lstat(dir->d_name, &sb) == -1) {
          perror("lstat");
          exit(EXIT_FAILURE);
        }
        if (sb.st_uid != 0) {
          printf("%s %llu 
", dir->d_name, (unsigned long long) sb.st_uid);
        }
      }
      closedir(katalog);
    }
  }
  return (0);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...