简体   繁体   中英

Read and write to same file

I am currently trying to write and read text to the same file in objective C.

Before I was trying to write to a bundled text file. Since, I have learned that this is unacceptable. I understand that there are permissions issues when it comes to writing to a file.

I am facing a couple errors to start with, mostly due to my inexperience with Objective C, especially IO. When I am trying to write to an existing text file, where do I place the file in the project? Currently I have just dragged and dropped the file into my project; I am assuming this is incorrect and that this is where most of my problems are coming from.

Here is my code for writing the text file:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myFile.txt"];

NSFileHandle *filehandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
[filehandle seekToEndOfFile];
[filehandle writeData:[@"Hello World" dataUsingEncoding:NSUTF8StringEncoding]];

Upon debugging, element filePath , contains a very long directory that isn't even located in my project directory.

Here is my code for writing to the file:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myFile.txt"];

NSError *error;
NSString *fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];

if (error)
    NSLog(@"Error reading file: %@", error.localizedDescription);

myArray = [fileContents componentsSeparatedByString:@"\n"];

I understand that the majority of the file is coming from where the file exists, I just have no idea where to put it. I would also like to be able to physically open and view the contents of the file if possible after the application closes.

The file system for iOS apps is somewhat restricted, a simple explanation of the rules would be as follows:

  • Your project, and all its resources are bundled.
  • A bundle is just a folder (usually named something like "YourAppName.app").
  • Once a bundle is deployed to the device your application doesn't have enough permissions to change (write/delete/rename/etc) files within the bundle.
  • When a bundle is installed it is also sandboxed.
  • A sandbox is just a folder containing your bundle and some other files and folders that your app needs to run.
  • You have write permissions to some of the folders in the sandbox, namely the "Documents" folder and the "Caches" folder.
  • You cannot access any files outside your application's sandbox.

The typical folder structure is:

SandboxFolder
|
|--- Documents <-- this is the folder you are writing to in your code
|
|--- YourAppName.app <-- this is your bundle folder
|
|--- Library
|    |
|    |--- Caches
|    |
|    |--- Preferences
|
|--- tmp

So in short, any files that you add to your project will end up in your application's bundle, you can read files within your application, the easiest way to find files within your bundle is to use the utility method - (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension you can find information about that method in the NSBundle documentation .

What you are doing in your code examples is good for reading and writing to a file in the documents folder (within your sandbox), that's fine but remember that if your application supports iCloud files in the documents folder will be uploaded to iCloud automatically. Take a look at the iCloud documentation for more information.

Finally to get a better idea of what the folder structure looks like (it's very similar between the simulator and the actual device) you can use finder to take a look, just follow these steps:

    // print the path to the documents folder to the console //
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"Documents path: %@", documentsDirectory);
  • In the console, look for the documents path (search for "Documents path:") and copy it
  • Go to finder and open the menu Go -> Go to folder... from the menu bar
  • Paste the path into the field and press ok
  • A new window will open with the documents folder, if you go up one level you will be at the root of your sandbox and will be able to see your app bundle and navigate freely to open files and get familiar with the structure.

Keep in mind that to see the files within your bundle you have to right click it and select "show package contents" from the context menu.

I hope this helps.

If you are trying out in simulator and wants to open it up in the mac

copy the file path from log [dont include the file name] Open finder>GO>Go to Folder A window opens paste the path and press enter

Result : A window in finder opens showing the folder and the file inside

As mentioned by others, files in your project end up in your bundle, so you'll never be able to write to them (you can/could on a Mac for old-fashioned non-signed apps - but you shouldn't, anyway).

What you can do is

  1. Include the file in the bundle.
  2. On the first run, read it, then write the whole contents to your Documents folder.
  3. Make sure you set a flag somewhere that you have completed the first run set-up, so it won't happen the next time around. If you wish, you can use the existence of the file in the Documents directory to determine that it has been copied over (kind of self-documenting and easy to keep updated).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM