我正在尝试找到是否使用C
安装了less
(不使用系统调用)。但是我对变量的复制有问题。字符串的内容被截断:
int ret;
char * pathValue;
char * pathValue2;
char *token3;
char * new_str ;
int pathlength;
pathValue = getenv ("PATH");
if (! pathValue) {
printf ("'%s' is not set.n", "PATH");
}
else {
printf ("'%s' is set to %s.n", "PATH", pathValue);
}
pathlength = sizeof(pathValue)/sizeof(char);
pathValue2 = malloc(sizeof(pathValue));
strncpy(pathValue2, pathValue, pathlength);
printf ("pathValue2 is to %s.n", pathValue2);
token3 = strtok(pathValue2, ":");
ret = 1;
printf("Looking for lessn");
while( token3 != NULL ) {
printf("Looking for less %sn", token3);
if((new_str = malloc(strlen(token3)+strlen("/less")+1)) != NULL) {
new_str[0] = ' ';
strcat(new_str,token3);
strcat(new_str,"/less");
printf( " %sn", new_str );
if (file_exist (new_str)) {
printf("Found lessn");
ret=0;
}
free(new_str);
} else {
printf("malloc failed!n");
}
token3 = strtok(NULL, ":");
}
free(pathValue2);
如果我运行程序,则第一个变量是我正确的PATH
,但是当我复制它时,它已被截断。这里怎么了?
$ ./a.out 'PATH' is set to /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games. pathValue2 is to /usr/loc. Looking for less Looking for less /usr/loc /usr/loc/less
我相信,问题在这里
pathlength = sizeof(pathValue)/sizeof(char);
在这种情况下,pathValue
是指指针,sizeof(pathValue)
仅产生指针大小的值,而不是字符串。。
您想要的是使用strlen()
。
另外,如下注释中所述,C标准保证sizeof(char)
始终产生1
的值。因此,可以从计算中删除。/