2015-10-17 143 views
-1

當我使用目錄ňGPG錯誤發生:GPG:沒有這樣的目錄或文件,但它具有 我有:如何連接字符串

char directory[100]="/tmp/hello.txt" 

有一個代碼

int s = system("echo password | gpg -c --passphrase-fd 0 directory"); 

的信息如果我寫而不是目錄'/tmp/hello.txt'它將工作 也許問題與''

+1

順便說一句,調用外部工具使用'系統()'是你應該避免(如果可能的依賴性管理是有問題的,一個外殼與它分開,等等)。在這種情況下,請查看[GPGme](https://www.gnupg.org/(es)/related_software/gpgme/index.html),它*可能會滿足您的需求。 –

+0

也gpg可能不在你的路徑 – arved

+0

不要在多用戶機器上這樣做:當GnuPG執行時,每個人都能夠讀取你的密碼短語! –

回答

1

C不會自動替換標識符的出現與它的價值。不過,預處理器會這樣做。你可以定義一個宏

#define directory "/tmp/hello.txt" 

,然後做

int s = system("echo password | gpg -c --passphrase-fd 0 " directory); 

concatenates弦在「預處理時間」,甚至在編譯時間。另一種方法是使用strncat在運行時來連接兩個字符串:

char str[128] = "echo password | gpg -c --passphrase-fd 0 "; 
strncat(str, directory, sizeof(str) - strlen(str)); 

爲了能夠reappend你可以存儲strlen(str)字符串,一個空字節寫入它的每一個時間,然後調用strncat

void append(const char* app) { 
    static const size_t len = strlen(str); 

    str[len] = '\0'; 
    strncat(str, app, sizeof(str) - len); 
} 
+0

謝謝,但我的目錄取決於緩衝區,所以目錄不是恆定的,它會改變 – John

+0

@John看我的編輯。 – Downvoter

+0

對不起,但我應該使用該系統,因爲作爲命令 – John

1

這是從一個重複的問題:pass parameter using system command

顯示如何局部變量內容傳遞給系統命令

這裏是建議的代碼,備註:usernamepassword是局部變量:

char cmdbuf[256]; 
snprintf(cmdbuf, sizeof(cmdbuf), 
     "net use x: \\\\server1\\shares /user:%s %s", 
     username, password); 
int err = system(cmdbuf); 
if (err) 
{ 
    fprintf(stderr, "failed to %s\n", cmdbuf); 
     exit(EXIT_FAILURE); 
} 
+0

感謝上一個錯誤修正,但另一個錯誤發生sh:2語法'|'意外的 – John

+0

建議在您的問題中附加編輯,以準確顯示您的修改後的代碼。 – user3629249