As I need to read a file when my app is launched and write it sometimes while using it, I tried to reach it with :
NSString *dataFile = [[NSBundle mainBundle
#import "ViewController.h"
@interface ViewController ()
@property (strong, nonatomic) IBOutlet UITextView *txtWriteText;
@property (strong, nonatomic) IBOutlet UIButton *btnWriteFile;
@property (strong, nonatomic) IBOutlet UIButton *btnReadFile;
@property (strong, nonatomic) IBOutlet UILabel *lblReadText;
- (IBAction)btnWriteFileTouched:(id)sender;
- (IBAction)btnReadFileTouched:(id)sender;
@property NSFileManager *filemgr;
@property NSString *docsDir;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_filemgr =[NSFileManager defaultManager];
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
_docsDir = dirPaths[0];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)btnWriteFileTouched:(id)sender {
NSString *filePath = [_docsDir stringByAppendingPathComponent: @"texfile.txt"];
NSData *databuffer = [@"PREFIX: " dataUsingEncoding: NSASCIIStringEncoding];
[_filemgr createFileAtPath: filePath contents: databuffer attributes:nil];
NSFileHandle *file = [NSFileHandle fileHandleForWritingAtPath: filePath];
if (file == nil){
NSLog(@"Failed to open file");
return;
}
NSMutableData *data = [NSMutableData dataWithData:[_txtWriteText.text dataUsingEncoding:NSASCIIStringEncoding]];
[file seekToEndOfFile];
[file writeData: data];
[file closeFile];
}
- (IBAction)btnReadFileTouched:(id)sender {
NSString *filePath = [_docsDir stringByAppendingPathComponent: @"texfile.txt"];
NSData *databuffer;
NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath: filePath];
if (file == nil){
NSLog(@"Failed to open file");
return;
}
databuffer = [file readDataToEndOfFile];
[file closeFile];
NSString *datastring = [[NSString alloc] initWithData: databuffer encoding:NSASCIIStringEncoding];
_lblReadText.text = datastring;
}
@end