2012-09-26 55 views
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 !"); 
} 

不知道這些字符串是怎麼來的不一樣。

+0

你是否以root身份運行?當你printf()'它們(或在調試器中)時,字符串會說什麼? –

+0

'fread'返回什麼?另外,如果一個函數失敗(如'stat'),錯誤在'errno'中。 –

+0

另一件事,請在問題中包含程序的實際輸出。 –

回答

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

echo結束應以換行符'\n',ASCII碼10這兩個字符串之間的區別呼應的字符串。與

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

嘗試它在另一方面,一個FILE*開始與popen應該與pclose封閉,不與fclose

+0

echo -n $ HOME/file.sh工作!!但在實際使用情況下,這是動態的。它在那裏工作 –

+0

你也可以檢查'echo'ed字符串是否以換行符結束,如果是的話,用緩衝區中的''\ 0''覆蓋它。 –

+0

Thanks guys !!它現在正在工作! –

相關問題