我有一些在 Objective-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,无法准确指出它。
最佳答案
这就是,固定和简化的:
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 = strdup(app_begin+1);
else
*app_name = strdup(full_path);
} else {
app_begin = app_end;
while (*(--app_begin) != '/') {}
diff = app_end - app_begin;
*app_name = malloc(diff);
strncpy(*app_name, app_begin+1, diff-1);
}
}
请注意,您的代码存在内存泄漏。 extract_app_name
的调用者应在使用完字符串后释放该字符串。
关于C 代码保留先前设置的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8720292/