- 论坛徽章:
- 0
|
结果输出正常,但最后一行出现段错误,用strace跟踪发现一下错误:
4709 write(1, "who2_24 509 rwxrwxr-x\n", 23) = 23
4709 stat64("/home/spring/c_workspace/dec_13/upp/ch2/precious_time", {st_mode=S_IFDIR|0775, st_size=4096, ...}) = 0
4709 write(1, "precious_time 509 rwxrwxr-x\n", 29) = 29
4709 getdents(3, /* 0 entries */, 3276 = 0
4709 --- SIGSEGV (Segmentation fault) @ 0 (0) ---
4709 +++ killed by SIGSEGV +++
程序如下:
/* ls1_27.c - a sort of program implementing the utility 'ls'
* features:list complicated details about a directory set by users.
* usage:
* building:gcc ls1_27.c -lm -o ls1_27
*/
#include<stdio.h>
#include<dirent.h>
#include<string.h>
#include<sys/types.h>
#include<math.h>
#include<sys/stat.h>
#define LEN 64
#define MSIZE 9
void print_mode(mode_t m)
{
int mode[MSIZE];
int i=MSIZE-1,j;
for(;i>=0;i--)
{
j=MSIZE-i-1;
mode[j]=m/pow(2,i);
m=m%(int)pow(2,i);
if(j%3==0)
{
if(mode[j]==1)printf("r" ;
else printf("-" ;
}
else if(j%3==1)
{
if(mode[j]==1)printf("w" ;
else printf("-" ;
}
else
{
if(mode[j]==1)printf("x" ;
else printf("-" ;
}
}
printf("\n" ;
}
int main(int argc,char * argv[])
{
const char * ccPathName="/home/spring/c_workspace/dec_13/upp/ch2";
char ccPathName2[LEN];
DIR * DD=opendir(ccPathName);
struct dirent stDir,*pstDir;
printf(ccPathName);
printf(":\n" ;
while((pstDir=readdir(DD))!=NULL)
{
printf("%s ",pstDir->d_name);
memmove(ccPathName2,ccPathName,strlen(ccPathName));
strcat(ccPathName2,"/" ;
strcat(ccPathName2,pstDir->d_name);
struct stat * ssBuf;
stat(ccPathName2,ssBuf);
mode_t st_mode2=(ssBuf->st_mode&0777);
printf("%d ",st_mode2);
print_mode(st_mode2);
memset(ccPathName2,0,sizeof(ccPathName2));
}
close(DD);
return 0;
}
|
|