2015-07-19 60 views
-1

我想通過命令行參數,然後適當連接生成shell命令,以便我可以使用system()運行它們(我知道這不是可取的,有更好的方法,但我被問到只用這種方式做)。但是在串接字符串時出現了一些問題,我通過了 這裏是代碼(我已經在每一步打印了所有內容以獲得清晰的理解,並且我還沒有編寫system()調用,首先我需要對此進行排序連接出):strcat正常工作

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
int main(int argc, char *argv[]) { 
    char* path=argv[1]; 
    char* oldName=argv[2]; 
    char* newName=argv[3]; 
    char* command1="cd "; 
    char* command2="ren "; 
     printf("\n\n%s\n%s\n%s\n%s\n%s\n",command1,command2,path,oldName,newName); 
    strcat(command1,path); 
    printf("\n\n%s\n%s\n%s\n%s\n%s\n",command1,command2,path,oldName,newName); 
    strcat(oldName," "); 
    strcat(oldname,newName); 
    printf("\n\n%s\n%s\n%s\n%s\n%s\n",command1,command2,path,oldName,newName); 
    strcat(command2,oldName); 
    printf("\n\n%s\n%s\n%s\n%s\n%s\n",command1,command2,path,oldName,newName); 

    return 0; 
} 

但是,在將command1連接到路徑之後,所有事情都會變得混亂起來。

http://i.stack.imgur.com/vPxxD.png

+0

參見[修改-字串文本](http://stackoverflow.com/questions/ 5464183 /修改字符串文字) – amdixon

+0

擺脫所有這些垃圾並使用'snprintf' –

+0

到目前爲止,您在C中學習了多少字符串? – immibis

回答

-1

需要使用的字符緩衝區以防止strcat的崩潰分配空間,這樣的:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
int main(int argc, char *argv[]) { 
    char* path=argv[1]; 
    char oldName[256]; 
    char* newName=argv[3]; 
    char command1[256]; 
    char command2[256]; 
    strcpy(command1, "cd "); 
    strcpy(command2, "ren "); 
    strcpy(oldName, argv[2]); 
    printf("\n\n%s\n%s\n%s\n%s\n%s\n",command1,command2,path,oldName,newName); 
    strcat(command1,path); 
    printf("\n\n%s\n%s\n%s\n%s\n%s\n",command1,command2,path,oldName,newName); 
    strcat(oldName," "); 
    strcat(oldName,newName); 
    printf("\n\n%s\n%s\n%s\n%s\n%s\n",command1,command2,path,oldName,newName); 
    strcat(command2,oldName); 
    printf("\n\n%s\n%s\n%s\n%s\n%s\n",command1,command2,path,oldName,newName); 

    return 0; 
} 
+2

對於包含路徑和少數文件名的命令行來說,256個字節就足夠了......對。 – Potatoswatter

+0

幫了很多。謝謝 –

+0

@Patatoswatter我知道你在諷刺,但我想指出*單個路徑有時會超過256個字符。這是Windows和* nix上的一個實際問題。 – immibis

1

strcat作品通過從源字符串到目的字符串的末尾複製字節。問題是,你的目的地的字符串是:

  1. 常量字符串(和可能不重寫存儲器)
  2. 沒有足夠長的時間來保存整個結果

你或許應該創建一個字符緩衝區如char buffer[1024]來保存命令並使用snprintf將命令格式化爲緩衝區。

+0

更好,但仍然不夠實際使用。要麼用'strlen'來計算實際需要的大小,要麼讓它變得太大,或者做真正的字符串處理而不是'strcat'。 – Potatoswatter

+0

是的,在真實應用程序中,您必須處理任意大小的輸入字符串。如果你沒有正確確定緩衝區的大小,使用'strcat'是很危險的,這是安全漏洞的常見來源。使用'snprintf'將防止緩衝區溢出,但輸出字符串將被截斷,這不是你想要的。 – EricS

1

strcat預計目的地足夠大以容納結果。至quote

指向目標數組的指針,它應該包含C字符串,並且要足夠大以包含連接的結果字符串。