我已經獲得了一些在Objective-C應用程序中運行的C代碼。我從互聯網上獲取了這些代碼。從前面的設置中保留字符的C代碼
static void extract_app_name(const char *all_arguments, char **app_name) {
char *full_path, *app_end, *app_begin; //, *app_name_temp;
size_t diff;
if (all_arguments == NULL || app_name == NULL) {
return;
}
full_path = (char*)all_arguments + sizeof(int);
app_end = strcasestr(full_path, ".app");
if (app_end == NULL) {
app_begin = strrchr(full_path, '/');
if (app_begin != NULL) {
*app_name = malloc(app_begin+1);
*app_name = strdup(app_begin+1);
} else {
*app_name = strdup(full_path);
}
} else {
app_begin = app_end;
while (*(--app_begin) != '/') {}
diff = app_end - app_begin;
char *app_name_temp[diff]; // = malloc(diff);
*app_name_temp = malloc(diff);
*app_name = malloc(diff);
strncpy(*app_name_temp, app_begin+1, diff-1);
app_name_temp[diff]='\0';
app_name = strcpy(*app_name, *app_name_temp);
}
}
此代碼的目的是從完整路徑中提取應用程序名稱。如果應用程序以.app
擴展名命名,則它會從.app所產生的任何內容中提取名稱。
例如,以下內容:
extract_app_name("/Applications/Google Chrome.app/Contents/Versions/16.0.912.63/Google Chrome Helper.app/Contents/MacOS/Google Chrome Helper", &app_name);
NSLog(@"First App is: %s", app_name);
extract_app_name("/System/Library/Frameworks/QuickLook.framework/Resources/quicklookd.app/Contents/MacOS/quicklookd", &app_name);
NSLog(@"Next App is: %s", app_name);
extract_app_name("/System/Library/CoreServices/Dock.app/Contents/XPCServices/com.apple.dock.extra.xpc/Contents/MacOS/com.apple.dock.extra", &app_name);
NSLog(@"Next App is: %s", app_name);
extract_app_name("/Applications/Tiny", &app_name);
NSLog(@"Next App is: %s", app_name);
應該輸出這樣的:
First App is: Google Chrome
Next App is: quicklookd
Next App is: Dock
Next app is: Tiny
一般情況下,這是正確的。但是,如果我連續4-5次運行應用程序,我的輸出有時不會總是成功。有時第二個應該輸出quicklookd
的應用程序實際上會轉儲quicklookdome
(它保留了第一個應用程序名稱的一部分)。
我懷疑它與變量沒有被正確初始化,並保留內存中已有的內容。我只是不知道C足以指出它。
請注意,每次調用函數時,都應該調用'free(app_name)'來避免內存泄漏。這是因爲該函數使用'malloc'來獲取一些內存來放入字符串。 – v1Axvw 2012-01-03 23:50:20
行'* app_name = malloc(app_begin + 1);'也因爲幾個原因沒有意義;你將一個指針作爲大小傳遞給'malloc',並且在爲'* app_name'賦值後立即傳遞'strdup'返回的值。 – AusCBloke 2012-01-04 00:02:21