- 论坛徽章:
- 0
|
在第二版的apue中文p101 的这个函数:
static int /* we return whatever func() returns */
75 dopath(Myfunc* func)
76 {
77 struct stat statbuf;
78 struct dirent *dirp;
79 DIR *dp;
80 int ret;
81 char *ptr;
82
83 if (lstat(fullpath, &statbuf) < 0) /* stat error */
84 return(func(fullpath, &statbuf, FTW_NS));
85 if (S_ISDIR(statbuf.st_mode) == 0) /* not a directory */
86 return(func(fullpath, &statbuf, FTW_F));
87
88 /*
89 * It's a directory. First call func() for the directory,
90 * then process each filename in the directory.
91 */
92 if ((ret = func(fullpath, &statbuf, FTW_D)) != 0)
93 return(ret);
94
95 ptr = fullpath + strlen(fullpath); /* point to end of fullpath */
96 *ptr++ = '/';
97 *ptr = 0;
98
99 if ((dp = opendir(fullpath)) == NULL) /* can't read directory */
100 return(func(fullpath, &statbuf, FTW_DNR));
101
102 while ((dirp = readdir(dp)) != NULL) {
103 if (strcmp(dirp->d_name, ".") == 0 ||
104 strcmp(dirp->d_name, "..") == 0)
105 continue; /* ignore dot and dot-dot */
106
107 strcpy(ptr, dirp->d_name); /* append name after slash */
108
109 if ((ret = dopath(func)) != 0) /* recursive */
110 break; /* time to leave */
111 }
112 ptr[-1] = 0; /* erase everything from slash onwards */
113
114 if (closedir(dp) < 0)
115 err_ret("can't close directory %s", fullpath);
116
117 return(ret);
118}
ptr[-1] = 0; 怎样起到 erase everything from slash onwards的作用的???
作了一个小测试:
1 #include<stdio.h>
2 #include<stdlib.h>
3
4 int
5 main(void)
6 {
7 char *p;
8 int i;
9 p=(char *)malloc(sizeof("abcdefg")*10);
10 if (p!=NULL){
11 p="abcdefg"+strlen("abcdefg");
12 p=p-3;
13 printf(p);
14 p[-1]=0;
15 }
16 exit(0);
17 }
gcc 编译通过 但是运行a.out 就得到:
Bus error: 10 (core dumped)
apue里的示例代码却可以编译运行
记忆中array i不能为负数丫
十分疑惑 请各位大大解答
谢谢
[ 本帖最后由 坏坏小少 于 2007-3-28 17:40 编辑 ] |
|