I am making a simple command line tool where the user enters a username and password (I don’t care about encryption
as this is only an exercise) and their age and this data is written to a file. This is the code I have:
char username[40];
char password[40];
int age = 0;
NSString *path = [NSString stringWithFormat:@"%@/Documents/config.txt", NSHomeDirectory()];
NSFileManager *fileManager = [[NSFileManager alloc]init];
//Username Input
NSLog(@"Pick a username (less then 40 letters):");
scanf("%s", username);
NSString *usernameString = [[NSString alloc] initWithBytes:username
length:39
encoding:NSUTF8StringEncoding];
//Password Input
NSLog(@"Pick a password (less then 40 letters):");
scanf("%s", password);
NSString *passwordString = [[NSString alloc] initWithBytes:password
length:39
encoding:NSUTF8StringEncoding];
//Age Input
NSLog(@"What's your age?");
scanf("%i", &age);
NSString *finalContents = [NSString stringWithFormat:@"%@\n%@\n%i", usernameString, passwordString, age];
NSData *dataContent = [finalContents dataUsingEncoding:NSUTF8StringEncoding];
[fileManager createFileAtPath:path contents:dataContent attributes: nil];
When I open up the file produced, it has the content:
(null)
(null)
18
I inputted a string less then 40 characters for both the username and password and the number 18 for the age, so it appears that only the age is working.
Thanks in advanced.
EDIT: The file has the content “(null) (null) 18” with line breaks in between, but they are not showing up in my post.
Try using
stringWithCString:encoding:.