我正在嘗試在 linux 中創建一個檔案,并使用system()C 程式中的函式為其賦予可執行權限。這是代碼:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char *argv[], char *envp[]){
char s[100];
strcpy(s, "touch ");
strcpy(s, argv[1]);
strcpy(s, "; chmod a x ");
strcpy(s, argv[1]);
system(s);
return 0;
}
但是,當我使用引數“abs”呼叫編譯檔案時(考慮我想要“abs”作為要創建的檔案的名稱),它會給出這樣的輸出:
sh: 1: abs: not found
如何修復?重要的是我必須使用 C 編程和system()函式。
uj5u.com熱心網友回復:
看來這個答案對于未來的讀者來說是無法理解的,讓我試著解釋一下strcpy和strcat有什么區別
- strcpy()將一個字串復制到另一個字串。
- strcat()函式通過將源字串附加到目標字串來連接字串。
在原始代碼中,每次呼叫“ strcpy ”函式時,緩沖區中的前一個值都會被覆寫。
char s[100];
strcpy(s, "touch "); // s = touch
strcpy(s, argv[1]); // s = abc (argv[1] value)
strcpy(s, "; chmod a x "); // s = ; chmod a x
strcpy(s, argv[1]); // s = abc (argv[1] value)
system(s); // execute s = abc
最后,由于“ s ”是“ abc ”,system() 函式嘗試執行它,這會產生以下錯誤:
sh: 1: abs: not found
在修改后的版本中,新值不會覆寫以前的值,而是附加到緩沖區中。
char s[100];
strcpy(s, "touch "); // s = touch
strcat(s, argv[1]); // s = touch abc
strcat(s, "; chmod a x "); // s = touch abc; chmod a x
strcat(s, argv[1]); // s = touch abc; chmod a x abc
system(s); // execute s = touch abc; chmod a x abc
uj5u.com熱心網友回復:
strcpy將一個字串復制到另一個,使用 strncat (3) 連接字串。
你的代碼應該是這樣的:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define ARRAY_SIZE(X) sizeof(X)/sizeof(X[0])
int main(int argc, char *argv[], char *envp[]){
char s[100];
strncat(s, "touch ", ARRAY_SIZE(s) - 1 - strlen(s));
strncat(s, argv[1], ARRAY_SIZE(s) - 1 - strlen(s));
strncat(s, "; chmod a x ", ARRAY_SIZE(s) - 1 - strlen(s));
strncat(s, argv[1], ARRAY_SIZE(s) - 1 - strlen(s));
system(s);
return 0;
}
uj5u.com熱心網友回復:
代碼應更改為以下內容:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char *argv[], char *envp[]){
char s[100];
strcpy(s, "touch "); //s = "touch "
strcat(s, argv[1]); //s = "touch " argv[1]
strcat(s, "; chmod a x "); //s = "touch " argv[1] "; chmod a x "
strcat(s, argv[1]); //s = "touch " argv[1] "; chmod a x " argv[1]
system(s); //system("touch " argv[1] "; chmod a x " argv[1])
return 0;
}
非常感謝評論員!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/487812.html
上一篇:為函式引數指定暫存器?
