How can I get data from a file in the documents folder

I am new to xcode and c object.

Firstly, I created a file in the document directory and it was created, and now I need how I can read data from this file, for example, whether the file contains a specific line or not.

How can i get this

+7
source share
4 answers

You can follow my answer here by saving and extracting plist files

Array from file in Xcode

+1
source

The following method will get the contents of the file into a string.

+ (id)stringWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error 

Then you can find out if the returned string contains the specified substring:

 NSRange textRange; textRange =[string rangeOfString:@"ohai"]; if(textRange.location != NSNotFound) { //String contains substring "ohai" } 

Hope this helps.

0
source

just as you write, you can get the data, suppose you want to get the image from the document folder, and then see this code -

 NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]]; NSString *fileName = [stringPath stringByAppendingFormat:@"/image.jpg"]; //fileName is your image path and image.jpg is your image name which is saved in documents folder... NSData *retrieveData = [NSData dataWithContentsOfFile:fileName]; UIImage *newImage = [UIImage imageWithData: retrieveData]; 

in this case instead

 [data writeToFile:fileName atomically:YES]; 

you need to write

 NSData *retrieveData = [NSData dataWithContentsOfFile:fileName]; 

lines. And you can get all kinds of data.

Thanks!

0
source

You can read data from a file in the document folder as follows:

  NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/<pathofFile>"]; NSString *fileContent = [[NSString alloc] initWithContentOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; 

Now you can use the NSString methods to find the substring in fileContent.

0
source

All Articles