How to get and set correct current path - objective-c

in my simple command line program, I try to write a string into a text file,
[str writeToFile:#"myfile.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
when I run my exec file via finder, I expect "myfile.txt" be created in the same folder that exec file is, but it was made in "/users/me"
later I tried to get current path of my program via these codes
NSFileManager *filemgr;
NSString *currentpath;
filemgr = [[NSFileManager alloc] init];
currentpath = [filemgr currentDirectoryPath];
NSLog(#"Current path is : %#",current path);
and I found out that regardless of the location of my exec file, the current path always is "/users/me". is there any way to get correct path?

You can use the instance returned from the defaultManager method of NSFileManager to manipulate your current path:
NSString *currentpath = [[NSFileManager defaultManager] currentDirectoryPath];
or
[[NSFileManager defaultManager] changeCurrentDirectoryPath:#"/new/path/"];
You can get the path of your executable from the bundlePath method of the bundle:
NSString *path = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];

Related

Can't find my file after writeToFile

I was trying to create a CSV file using xcode but I can't seem to find the file anywhere after creation.
One solution I found was going into products folder itself but it isn't there.
Another solution that didn't work: Window-> Devices-> look at the installed apps of the devices but the container is empty.
Here is my code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *root = [documentsDir stringByAppendingPathComponent:#"test.csv"];
// Append file here
temp = [NSString stringWithFormat:#"%.0f", (float)*samples];
if (![[NSFileManager defaultManager] fileExistsAtPath:root]) {
[[NSFileManager defaultManager] createFileAtPath: root contents:nil attributes:nil];
NSLog(#"Route created");
}
NSError *error = nil;
NSLog(#"%#", root);
BOOL success = [temp writeToFile:root atomically:YES encoding:NSUTF8StringEncoding error:&error];
if(!success){
NSLog(#"fail to write to csv file");
}
It always is successful, but yet I can't find the file, also the file also seem to exists as it does not enter the if(fileExistsAtPath) after the first time.
The root directory is : /var/mobile/Containers/Data/Application/DDA4F37D-8D61-43F9-809C-31B09852B77F/Documents/test.csv
Edit: to make it clearer, I'm trying to retrieve it via xcode. Through finder so that I can get the csv file.
Any help is appreciated.

Copy contents of app to desktop programmatically

How can I copy my entire .app bundle ([[NSBundle mainBundle] bundleURL]) to my desktop programmatically?
Here is my code but not helping me.
NSString *sourcepath = [[NSBundle mainBundle] bundlePath];
NSString *destpath = [NSHomeDirectory() stringByAppendingPathComponent:#"Desktop"];
[[NSFileManager defaultManager] copyItemAtPath:sourcepath toPath:destpath error:nil];
You can use the standard NSFileManager methods
copyItemAtURL:toURL:error: or
copyItemAtPath:toPath:error:
to copy directories as well as files. From Apple's docs:
When copying items, the current process must have permission to read the file or directory at srcPath and write the parent directory of dstPath. If the item at srcPath is a directory, this method copies the directory and all of its contents, including any hidden files.
Mind that you have to manually remove an item (file/directory) at the destination with the same name if it already exists or else the copy will fail (again, as per Apple's docs).
Here's how I solved it may be this can be helpful for someone.
- (IBAction)createShortcut:(id)sender {
NSString *sourcepath = [[NSBundle mainBundle] bundlePath];
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
NSString *theDesktopPath = [paths objectAtIndex:0];
NSString *saveFilePath = [theDesktopPath stringByAppendingPathComponent:#"myApp.app"];
[[NSFileManager defaultManager] copyItemAtPath:sourcepath toPath:saveFilePath error:nil];
}

how to copy a file on the network in cocoa

I would like to copy the selected file from my computer to another computer on the same network. I tried to use NSFileManager but I was not successful. Could please help how to do it?
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString * filePath = [NSHomeDirectory() stringByAppendingPathComponent:
[NSString stringWithFormat:#"Documents/test"]];
NSString * filePath2 = [NSHomeDirectory() stringByAppendingPathComponent:
[NSString stringWithFormat:#"Shared/Test"]];
[fileManager copyItemAtPath:filePath toPath:filePath2 error:NULL];
[fileManager release];
2 suggestions:
1) as per the documentation, in this line the error should be "nil" not "NULL"
[fileManager copyItemAtPath:filePath toPath:filePath2 error:NULL];
2) Maybe the code is not finding the files. I notice you do not have any file extension on the paths (maybe "test" should be "test.txt"?). Most files have an extension even if you can't see the extension in the Finder. Get Info on the file to check its extension and fix the code if that's the case.

Copy contents of a directory to Documents directory

I have a problem, I need to move the contents of a Documents subdirectory to the 'root' of Documents Directory.
To do this, I thought to copy all the contents of the subdirectory to Documents directory and then delete my subdirectory.
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentinbox = [documentsDirectory stringByAppendingPathComponent:#"inbox"]
This is how I get the path of Documents directory, and the path of my subdirectory named inbox.
NSArray *inboxContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentinbox error:nil];
NSFileManager *fileManager = [NSFileManager defaultManager];
Then I create an array with all documents in the subfolder, and initialize the file manager.
Now I have to implement the for cycle that for each document copy the document from the subdirectory to the Documents Directory.
for(int i=0;i<[inboxContents count];i++){
//here there is the problem, I don't know how to copy each file
I would like to use the method moveItemAtPath, but I don't know how to get the path of each file.
Hope you can understand my problem,
Thanks for help
Nicco
You can use moveItemAtPath:toPath:error: as follows.
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentinbox = [documentsDirectory stringByAppendingPathComponent:#"inbox"];
//Initialize fileManager first
NSFileManager *fileManager = [NSFileManager defaultManager];
//You should always check for errors
NSError *error;
NSArray *inboxContents = [fileManager contentsOfDirectoryAtPath:documentinbox error:&error];
//TODO: error handling if inboxContents is nil
for(NSString *source in inboxContents)
{
//Create the path for the destination by appending the file name
NSString *dest = [documentsDirectory stringByAppendingPathComponent:
[source lastPathComponent]];
if(![fileManager moveItemAtPath:source
toPath:dest
error:&error])
{
//TODO: Handle error
NSLog(#"Error: %#", error);
}
}

Objective-C / Can't access (read) file in "Resources" folder

This is probably a very easy problem to solve but i have not succeeded. I have copied the file "questions_famquiz_easy_110326.txt" to the resources folder and now want to access (read) it and NSLog it to see that i am able to read it.
The code below is from one of the tests i have done based on examples that i have found on the web.
I am trying to access a txt-file in the Resources folder and fail to do so. I have searched for a solution, tested a lot, but not succeeded.
I am testing with the following code:
NSLog(#"\n \n >>>>>>viewDidLoad<<<<<<<<<");
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docsDirectory stringByAppendingPathComponent:#"questions_famquiz_easy_110326.txt"];
if(![fileManager fileExistsAtPath:filePath])
{
NSData *data = [NSData dataWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingString:#"/questions_famquiz_easy_110326.txt"]];
[data writeToFile:filePath atomically:YES];
}
NSString *myString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"myString: %#", myString);
NSLog(#"\n \n>>>>>>DONE WITH viewDidLoad<<<<<<<<<");
exit(0); //====EXIT JUST FOR THE TEST====<<<
The above code is located in the first viewController that is started.
The output i get is:
>>>>>>viewDidLoad<<<<<<<<<
2011-04-24 21:53:47.825 FamQuiz_R0_1[542:307] myString: (null)
2011-04-24 21:53:51.044 FamQuiz_R0_1[542:307]
>>>>>>DONE WITH viewDidLoad<<<<<<<<<
Could someone nice help me to solve this?
update:
Here is the filePath:
2011-04-24 22:38:08.562 FamQuiz_R0_1[637:307] filePath: /var/mobile/Applications/7F5FDB03-0D22-46BC-91BC-4D268EB4BBEB/FamQuiz_R0_1.app/questions_famquiz_easy_110326.txt
Here is where i have placed the file:
PROBLEM SOLVED:
NSString *myString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
When i used the above it did not work, when i used the below it worked and printed out the text.
NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath];
You're not reading from the resources folder. You're trying to read from the document directory. So getting back nil makes sense since the file doesn't exist there.
Change:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docsDirectory stringByAppendingPathComponent:#"questions_famquiz_easy_110326.txt"];
to:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"questions_famquiz_easy_110326" ofType:#"txt"];
and it should work for you.