1

我正在运行以下代码来检查文件是否存在,但是将字符串传递给 stat 时,它返回失败。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>

int main ()
{
struct stat statbuf;
char tmp_buf1[100];
char result [100];
char result1[100]="/root/file.sh";
strcpy(tmp_buf1,"echo $HOME/file.sh");
FILE* fp;
fp = popen(tmp_buf1,"r");
printf("Name passed is:%s\n",tmp_buf1);
fread(result,1,sizeof(result),fp);
fclose (fp);
printf("The full path is  %s\n",result);
int rc = 0;

// To find out difference b/w the the strings, I am doing a strcmp, it is returning 10.
int r = strcmp(result,result1);

printf (" Return is = %d\n",r);
rc = stat(result, &statbuf);
if ( rc == -1 ) {
    printf("File is NOT HERE!\n");
    printf("Return Code = %d",rc);
   }
else
    printf("Found it !");
}

不知道为什么这些字符串不一样。

4

1 回答 1

3
strcpy(tmp_buf1,"echo $HOME/file.sh");

echo结束它应该用换行符'\n',ASCII码10回显的字符串。这就是两个字符串之间的区别。试试看

strcpy(tmp_buf1,"echo -n $HOME/file.sh");

另一方面,FILE*打开的 withpopen应该用 关闭pclose,而不是用关闭fclose

于 2012-09-26T20:16:19.110 回答