Search code examples
objective-cconsole-applicationuser-inputfilepathnsfilemanager

How to create a filepath from console input in Objective-c?


For my application, I need a user to be able to enter some input through the console, and that string, except uppercased, to be part of a path file. I have the following code, but while everything appears to run smoothly, the file isn't actually created. I don't even get the error message through my if block.

#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;}

Solution

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

    should be:

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

    or

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

    Your version was creating an array of the format string and the components, and assigning the array to dirUsername, but this version uses NSString stringWithFormat:.

    (stringByAppendingPathComponent may be better, though: [[@"~/Desktop/MyFiles" stringByAppendingPathComponent:stringUppercase] stringByExpandingTildeInPath];)