Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The system call</p> <pre><code>int stat(const char *path, struct stat *buf); </code></pre> <p>does not allocate memory for <code>*buf</code>.</p> <p>Either you stay with your declaration </p> <pre><code>struct stat *buf; </code></pre> <p>and allocate the memory by hand with</p> <pre><code>buf = (struct stat *) malloc(sizeof(struct stat)); </code></pre> <p>and free the memory with <code>free</code> at a place where you don't need <code>buf</code> anylonger</p> <p>or you change the declaration to</p> <pre><code>struct stat buf; </code></pre> <p>and let c allocate the memory for you.</p> <p>More over you should test failing of <code>stat</code> with <code>if(stat(t,&amp;buf) &lt; 0)</code> as recommended in the manual.</p> <p>Another error is, that you don't pass the filename to <code>stat</code> but the directory name.</p> <p>I appended a corrected version of your code.</p> <hr> <pre><code>#include&lt;sys/types.h&gt; #include&lt;time.h&gt; #include&lt;string.h&gt; #include&lt;dirent.h&gt; #include&lt;stdio.h&gt; #include&lt;sys/stat.h&gt; #include&lt;unistd.h&gt; void do_ls(char []); void show_file_info(struct stat *t){ printf("mode: %o\n",t-&gt;st_mode); if((t-&gt;st_mode &amp; S_IFMT) == S_IFDIR) printf("Is a dir\n"); else printf("Is not a dir\n"); printf("links: %d\n",t-&gt;st_nlink); printf("group: %d\n",t-&gt;st_gid); printf("user: %d\n",t-&gt;st_uid); printf("size: %d\n",t-&gt;st_size); printf("modtime: %s\n",ctime(&amp;t-&gt;st_mtime)); } int main(int num,char *a[]){ if(num==1){ do_ls("."); } else{ while(--num){ printf("%s :\n",*++a); do_ls(*a); } } } void do_ls(char dirname[]){ DIR *tem=opendir(dirname); struct dirent *direntp; struct stat buf; char t[256]; if(tem==NULL){ fprintf(stderr,"ls: cannot open %s\n",dirname); } else{ while((direntp=readdir(tem))!=NULL){ strcpy(t,dirname); printf("%s\n",direntp-&gt;d_name); strcat(t,"/"); strcat(t,direntp-&gt;d_name); if(stat(t,&amp;buf) &lt; 0){ perror(""); break; } else{ show_file_info(&amp;buf); } } closedir(tem); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload