c++ - 字符串的值不同,但打印它们显示相同的值

标签 c++ c strcmp stat

我正在运行以下代码来检查文件是否存在,但是当将字符串传递给 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 !");
}

不确定这些字符串为何不相同。

最佳答案

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

echo 以换行符 '\n' 结束应回显的字符串,ASCII 代码 10。这就是两个字符串之间的区别。尝试一下

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

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

关于c++ - 字符串的值不同,但打印它们显示相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12609529/

相关文章:

c++ - 我在 C++ 中看到了以下代码。它是定义的行为吗?

从 C 程序更改堆栈内存

c - 使用相同的代码,我从 ATMEGA16A 的两个端口得到两个不同的答案

使用 strcmp 函数时出现转换错误

c - 段错误处理 strcmp

c - 为什么我的程序打印的次数比预期多?

c++ - Boost 日志和动态加载的库

c++ - 双线性插值正弦图像失真 C++

c++ - std::replace 给出错误

c - 结构和类型定义