0

对于我的应用程序,我需要用户能够通过控制台输入一些输入,并且该字符串(大写除外)成为路径文件的一部分。我有以下代码,但虽然一切似乎运行顺利,但实际上并没有创建该文件。我什至没有通过我的 if 块收到错误消息。

#define DEBUGGER 1
NSLog (@"Username:");
char userInput[70];
fgets (userInput, sizeof userInput, stdin);
int c;
while ((c = getchar()) != '\n' && c != EOF);
if (userInput [strlen(userInput) - 1] == '\n') //In case the input string has # characters plus \n
    userInput[strlen(userInput) - 1] = '\0'; //Plus '\0', the '\n' isn't added and the if condition is false
NSFileManager * fm = [NSFileManager defaultManager];
NSString * string = [NSString stringWithUTF8String: userInput];
NSString * stringUppercase = [string uppercaseString];
NSString * dirUsername = [NSString stringWithFormat:@"~/Desktop/ProjAlleleData/Accounts/%@", stringUppercase.stringByExpandingTildeInPath];stringByExpandingTildeInPath];
#ifdef DEBUGGER
NSLog(@"DEBUGGER MESSAGE: Username Directory Path: %@", dirUsername);
#endif
if ([fm createDirectoryAtPath: dirUsername withIntermediateDirectories: YES attributes: nil error: NULL] != YES) {
    NSLog(@"Save File Creation Error.");
    return 1;}
4

1 回答 1

0
NSString * dirUsername = [@"~/Desktop/MyFiles/%@", stringUppercase stringByExpandingTildeInPath];

应该:

NSString *dirUsername = [NSString stringWithFormat:@"~/Desktop/MyFiles/%@", stringUppercase];
NSString *dirUsername2 = [dirUsername stringByExpandingTildeInPath];

或者

NSString *dirUsername = [[NSString stringWithFormat:@"~/Desktop/MyFiles/%@", stringUppercase] stringByExpandingTildeInPath];

您的版本正在创建格式字符串和组件的数组,并将该数组分配给 dirUsername,但此版本使用 NSString stringWithFormat:。

(不过,stringByAppendingPathComponent 可能会更好[[@"~/Desktop/MyFiles" stringByAppendingPathComponent:stringUppercase] stringByExpandingTildeInPath];:)

于 2013-07-29T16:26:54.847 回答