2012-01-26 52 views
2

即时尝试concatsomm字符串,并调用我的服务器上的exxt脚本,但即时通讯.net程序员和新的C和指针,所以不断弄乱...我是什么在这里做错了吗?如何字符串concat和调用系统的字符变量

或更好的问题将是我应该怎么做到这一点?

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(int argc, char *argv[]) 
{ 
    //location of expect script that ssh and gets info on other server 
    char str0[] = "./home/systemio/Develop/getfile "; 

    char* strP = argv[1]; 
    char str1 = (char)*strP; 
    char str2[] = " > file.txt"; 

    strcat(str0,str1); 

    strcat(str0,str2); 

    printf("%s\n", str0); 
    system(str0); 

    printf("Done!!!!\n"); 
    return 0; 
} 

回答

2

您可以分配缓冲区的系统命令,以保证肯定是有足够的空间来构建完整的命令:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(int argc, char* argv[]) 
{ 
    /* Ensure 1 argument supplied. */ 
    if (2 == argc) 
    { 
     /* malloc()ing the system command buffer means you can safely 
      edit 'util' and 'output' without being concerned about the 
      size of an array. 
      The '+2' is for the char from argv[1] 
      and for the terminating null character. */ 
     const char* util = "./home/systemio/Develop/getfile "; 
     const char* output = " > file.txt"; 
     char* str0   = malloc(strlen(util) + strlen(output) + 2); 

     if (str0) 
     { 
      if (sprintf(str0, "%s%c%s", util, *argv[1], output) > 0) 
      { 
       printf("%s\n", str0); 
       system(str0); 
       printf("Done!!!!\n"); 
      } 

      /* free() malloced memory. */ 
      free(str0); 
     } 
    } 

    return 0; 
} 
1

C中的连接并不像它在Java或C#中所做的那样。 (你不能这样做 “A” + “B”,并获得 “AB”)

阅读:http://cplusplus.com/reference/clibrary/cstring/strcat/

的strcat(DEST,SRC)

您需要预留空间目的地以确保附加的字符串适合目标变量。 (必须先有“A”然后复制“B”)。

我喜欢strcpy

4

这条线将无法正常工作:

strcat(str0,str1); 

这是因为str1不是字符串!这是一个单一的char。字符串只能是char指针或char数组。

正如其他人所指出的,str0不够大,所以您会覆盖内存,这将导致未定义的行为

如果我可以举一个替代的解决方案是什么你正在尝试做的:

char str[100]; 

sprintf(str, "./home/systemio/Develop/getfile %c > file.txt", argv[1][0]); 
printf("%s\n", str); 
system(str); 

编辑:为什么我用argv[1][0]

的原因解释是因为在这两条线问题:

char* strP = argv[1]; 
char str1 = (char)*strP; 

这两行从argv[1]得到第一个字符,间接 办法。如果你想整个的argv[1]然后我sprintf看起来是这样,而不是:

sprintf(str, "./home/systemio/Develop/getfile %s > file.txt", argv[1]); 
+0

为什么的argv [1] [0],而不仅仅是做argv [1]? – systemio

+0

,因为他只接受argv [1]的第一个字符,而不是整个字符串。 (看看%c而不是%s) –

+0

@systemio更新了我的答案。我还可以建议你阅读更多关于指针的信息,以及表达式行“* pointer”的作用? –