为什么strcmp不起作用?

时间:2015-04-21 21:44:31

标签: unix process popen strcmp

该计划运作良好。它验证参数是文件还是目录,并返回1或2.但strcmp不起作用,我不知道原因。

这是我的代码:

#DEFINE N 100
int main(int argc,char* argv[]) {

FILE *fp;
char cmd[N];
char result[N];
int i;

for(i=1;i<argc;i++){
    pipe(c2p);
    if (fork()==0){
        //Running the shell script
            sprintf(cmd,"/home/flory/os/verif.sh %s", argv[i]);
            fp = popen(cmd, "r");
            fgets(result, N, fp);
            pclose(fp);
            printf("%s",result);    
            if (strcmp(result,"1")==0){
                     //DO SOMETHING
            }
}

2 个答案:

答案 0 :(得分:0)

变量x还没有值。

您的意思是以下吗?

if (strcmp(result,"1")==0){
                 //DO SOMETHING
}

答案 1 :(得分:0)

除了您的问题中的可变混淆之外,请注意在阅读一行文字时尾随换行符会发生什么。来自linux手册页fgets(3):

   fgets() reads in at most one less than size characters from stream  and
   stores  them  into  the buffer pointed to by s.  Reading stops after an
   EOF or a newline.  If a newline is read, it is stored into the  buffer.
   A '\0' is stored after the last character in the buffer.

我写了一个类似你的小程序:

#include <stdio.h>

main()
{
  FILE      *fp;
  char bigbuf[10*1024];

  fp = popen("/bin/echo hello world", "r");
  fgets(bigbuf, sizeof bigbuf, fp);

  printf("length of bigbuf: %d\nlength of \"hello world\": %d\n", strlen(bigbuf), strlen("hello world"));
  exit(0);
}

运行它,我得到以下输出:

length of bigbuf: 12
length of "hello world": 11