2012-01-26 8 views
2

私はconcatsomm文字列にしようと私のサーバー上のexpextスクリプトを呼び出すが、イム.netプログラマーとCとポインタの新しいので、ここで間違っている?どのように文字列concatとchar呼び出しのシステムを呼び出す

またはもっとよく質問してください。どうすれば本当にこれを行うべきですか?

#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#で行われているようではありません。 (あなたが "" + "B" を行うと、 "AB" を取得することはできません)

読む:あなたは、スペースを確保する必要がhttp://cplusplus.com/reference/clibrary/cstring/strcat/

strcatは(DEST、SRC)

追加された文字列が出力先変数に収まることを確認してください。 (最初に "A"を付けてから "B"をコピーする必要があります)。

私はあなたが完全なコマンドを構築するのに十分なスペースが間違いなくあることを確認するために、システムコマンドのためのバッファを割り当てることができstrcpy

4

この行は動作しません。

strcat(str0,str1); 

str1は文字列ではないためです。それは単一のcharです。文字列は、char-pointerまたはchar-arrayだけです。

str0は十分に大きくないので、メモリが上書きされ、の動作が定義されていません

私はあなたがやろうとしているものへの代替ソリューションを与える可能性がある場合:

char str[100]; 

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

編集:私は理由があるため、これらの2つのラインであるargv[1][0]

を使用する理由の説明質問:

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

これらの2行は、最初の文字が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]の最初の文字だけをとるためです。 (%sの代わりに%cを見てください) –

+0

@systemio私の答えを更新しました。ポインタについてもう少し詳しくお読みください。また、 '* pointer'の式の行は何ですか? –

関連する問題