我需要将文件复制到当前的工作用户目录。
我确实喜欢这个
NSString *filepath = @"~/Desktop";
NSString *filename = @"newFile";
int status=system([[NSString stringWithFormat:@"touch %@/%@", filePath, filename]UTF8String]);
但这不是在桌面上创建文件。有人可以告诉我“~”的替代品来获取当前的工作用户吗?
我需要将文件复制到当前的工作用户目录。
我确实喜欢这个
NSString *filepath = @"~/Desktop";
NSString *filename = @"newFile";
int status=system([[NSString stringWithFormat:@"touch %@/%@", filePath, filename]UTF8String]);
但这不是在桌面上创建文件。有人可以告诉我“~”的替代品来获取当前的工作用户吗?
该~
字符在文件系统上下文中没有含义,它在 shell 上下文中具有含义,并且$HOME
作为Tilde Expansion的一部分被替换。来自 bash 人:
波浪号扩展
如果单词以不带引号的波浪号字符 (`~') 开头,则第一个不带引号的斜杠之前的所有字符(或所有字符,如果没有不带引号的斜杠)都被视为波浪号前缀。如果波浪号前缀中没有任何字符被引用,波浪号后面的波浪号前缀中的字符将被视为可能的登录名。如果此登录名是空字符串,波浪号将替换为 shell 参数 HOME 的值。如果 HOME 未设置,则替换执行 shell 的用户的主目录。否则,波浪号前缀将替换为与指定登录名关联的主目录。
因此,一种解决方案是,正如 Dolda2000 建议的那样,使用$HOME
代替,~
但在用户不是 root 的情况下它不起作用~root
(在这种情况下以 root 为例)。
更通用的解决方案是在调用中调用 shell system
。我不知道 Objective-C,但它与 bash 相结合,它看起来像:
int status=system([[NSString stringWithFormat:@"bash -c 'touch %@/%@'", filePath, filename]UTF8String])
让所有用户进入你的机器
for USER_DIR in $(ls /Users);
do {
*<write code here to implement something with each user>*;
}
done;
这是一个终端命令。与目标 c 中的system()一起使用。
NSString *filepath = [@"~/Desktop" stringByExpandingTildeInPath];
NSString *filename = @"newFile";
int status=system([[NSString stringWithFormat:@"touch %@/%@", filepath, filename]UTF8String]);
怎么用getenv("HOME")
?