Objective-C creating a text file with a string - objective-c

I'm trying to create a text file with the contents of a string to my desktop. I'm not sure if I'm doing it right, I don't get errors but it doesn't work either...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
NSString *desktopDirectory=[paths objectAtIndex:0];
NSString *filename = [desktopDirectory stringByAppendingString: #"file.txt"];
[myString writeToFile:filename atomically:YES encoding: NSUTF8StringEncoding error: NULL];

//Method writes a string to a text file
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = #"One\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}

You don't know if you're getting any errors because you're ignoring the returned YES/NO value of the -writeToFile:... method, and giving it no error pointer into which to record any possible failure. If the method returns NO, you'd check (and handle or present) the error to see what went wrong.
At a guess, the failure is due to the path you constructed. Try -stringByAppendingPathComponent: instead of -stringByAppendingString: ... this and its related methods properly handle paths.
The file probably is actually being created (ie, you might not be getting any errors after all). My guess is the file is created somewhere like "~/Desktopfile.txt" since your use of -stringByAppendingString: doesn't consider the string as slash-separated path. Check your home folder - I'll bet the file's there.

the problem is that the desktop directory string ends in nothing (no /). Check this out (on an iPhone) by using UIAlertview.

Related

Cocoa contents of directory

I have a group/folder with a series of text files. I need to get a path for each one so that I can read the contents, but I can't seem to get anything to work.
I've mucked about with [NSBundle pathsForResourcesOfType:#"txt" inDirectory:#"directoryName"] which gave me nothing but nulls or a single string that reads "Contents", [[NSFileManager defaultManager] enumeratorAtPath:#"directoryName"] which I have no idea what to do with once it's created, and [[NSFileManager defaultManager] contentsOfDirectoryAtPath:#"directoryName" error:nil].
I can't figure out what I'm doing wrong, and at this point I'm just grasping at straws. I went through 20 or 30 pages on here, none of which has really helped.
I should note that this is a Cocoa Application, not iOS.
If you want to read files in arbitrary directories, the path enumerator works nicely. A bit old fashioned, but that has its charm, too.
NSString *docPath = #"/tmp";
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:docPath];
NSString *filename;
while ((filename = [dirEnum nextObject])) {
//Do something with the file name
}
If you want to read from well-known and defined directories in your home directory, then you can use NSSearchPathForDirectoriesInDomains:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [paths objectAtIndex: 0];
This will give you your Documents directory, and when used with the snippet above, list all files in that folder and subfolders.
Notice that we are not really supposed to use our nice, old Unix paths any more, but instead refer URLs.
In that case, you get something like:
NSArray *URLs = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *docURL = URLs[0];
NSDirectoryEnumerator *URLEnum = [[NSFileManager defaultManager] enumeratorAtURL: docURL includingPropertiesForKeys: nil options: 0 errorHandler: nil];
NSString *filename;
while ((filename = [URLEnum nextObject])) {
// ...
}
Notice that enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: has all sorts of useful parameters, which you can read about in the docs.
Lets just take 1 of your 3:
[[NSFileManager defaultManager] contentsOfDirectoryAtPath:#"directoryName" error:nil]
You should include the error parameter and check what it contains
You need to supply a full path, not just a "directoryName"
As a result you'll get an array containing the file names of the files in the directory
So if you want the full path you can do:
NSString *directoryPath = ...;
NSArray *fileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:...];
for(NSString *fileName in fileNames) {
NSLog(#"%#", [directoryPath stringByAppendingPathComponent:fileName]);
}
The problem was that when adding the folder, I needed to create a reference to the folder as well. Xcode does not default to this option. I had initially chosen to simply create groups, and this does not do the job.
If your group is in your current project you can use:
NSString *path = [[NSBundle mainBundle] pathForResourcesOfType:#"txt" inDirectory:#"directoryName"]
this should work for you, I noticed that you tried something similar, but make sure you're using mainBundle.

Download a file from Dropbox and save to path

I am trying to save a file from dropbox in the following way:
NSString *fileName = [NSString stringWithFormat:#"/newFile.json"];
// Do any additional setup after loading the view, typically from a nib.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path2 = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:#"%#", fileName]];
[[self restClient] loadFile:fileName intoPath:path2];
the file is under apps/appname/sandbox/newFile.json
but I get this error:
2012-05-12 21:05:46.824 Quick Homework & business[934:707] [WARNING] DropboxSDK: error making request to /1/files/sandbox/newFile.json - File not found
but the file is there!!
I found out that in order to access al dropbox folders, even if in the sandbox folder, your app needs to be set to "full dropbox access", otherwise this error comes out. this problem though is there only when trying to download from dropbox, not when uploading or when loading the metadata in a UITableView.

How to save text file without overwritng in objective c

I am trying to write NSString to the file. It is writing successfully however I want to append the new string to new line.
How can do this?
You can read file content, append new data to that content and save new data to a file you use:
// Here you set your appending text.
NSString *yourAppendingText = #"yourAppendingText";
// Here you get access to the file in Documents directory of your application bundle.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [paths objectAtIndex:0];
NSString *documentFile = [documentDir stringByAppendingPathComponent:#"yourFile.txt"];
// Here you read current existing text from that file
NSString *textFromFile = [NSString stringWithContentsOfFile:documentFile encoding:NSUTF8StringEncoding error:nil];
// Here you append new text to the existing one
NSString *textToFile = [textFromFile stringByAppendingString:yourAppendingText];
// Here you save the updated text to that file
[textToFile writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil];

where does the text file I dragged to xcode go on the iphone/simulator?

I have some data in a .txt file that I dragged over to resources in xcode 4.2. I then use some methods that call upon this file, read it, and display it on the screen to the user. It works. My problem is writing to the end of the same file (aka updating the file based on something the user did) directly on the iphone/ the simulator. It does not write for I feel I am not calling upon the right location and perhaps method. This is my code to write to the end of file, if anyone knows why this is not working it would be tremendous help.
Thank you
-(void)updateFile:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//append filename to docs directory
NSString *myPath = [documentsDirectory stringByAppendingPathComponent:#"Mom.txt"];
fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:myPath];
dateCombinedString= [dateCombinedString lowercaseString];
writtenString= [[NSString alloc]initWithFormat:#", %#, %#, %#",dateString,trimmedString,ForDisplay];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[writtenString dataUsingEncoding:NSUTF8StringEncoding]];
[writtenString release]
}
The file you dragged to Xcode is inside your app resources. You can get the path to resource with this line of code:
NSURL* fileUrl = [[NSBundle mainBundle] URLForResource:#"Mom" withExtension:#"txt"];
However, you cannot modify the files in the resource directory therefore you should first copy that file to your document directory, then modify it with the code in the question.
Here is how you can copy file from resources if the file does not exist on the documents folder:
NSFileManager* fm;
fm = [NSFileManager defaultManager];
//only copy it from resources if it does not exits
if(![fm fileExistsAtPath:myPath]){
NSURL* myUrl = [NSURL fileURLWithPath:myPath];;
NSError* error = nil;
[fm copyItemAtURL:fileUrl toURL:myUrl error:&error];
//handle the error appropriately
}

Reading data from a file

I'm new to mac and Cocoa so I'm sorry if this is a stupid question..
I need to read all the lines I wrote on a file I saved on my desktop.
The file format is .txt; I tried with stringWithContentsOfFile but the program freezes.
I tried with GDB and I noticed that, while the path is correct, the string which is supposed to contain the data returns nil.
Am I missing something important?
You need to use a path not just the filename
NSString *string;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] != 0) {
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *newFile = [documentsDirectory stringByAppendingPathComponent:#"filename.txt"];
NSFileManager *fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:newFile]) {
string = [NSString stringWithContentsOfFile:newFile];
}
}
You will need to replace the documents directory for the bundle directory if you are reading from there.
EDIT
I jumped the gun. It seems that this is NOT an iPhone question. None-the-less, you will need to pass in the full path, not just the filename