Removing last line in a file iPhone iOS - iphone

How can I remove last line in a file in iOS.
Below is the code that let's me go to the end of file but then I don't know how to remove that last line.
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 *file = [NSString stringWithFormat:#"%#/%#.daa", documentsDirectory, MFILE_NAME];
NSFileHandle *aFileHandle = [NSFileHandle fileHandleForWritingAtPath:file];
//setting aFileHandle to write at the end of the file
[aFileHandle truncateFileAtOffset:[aFileHandle seekToEndOfFile]];
Thanks for your help.

Ok, after some documentation reading this is what I ended up with:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file = [NSString stringWithFormat:#"%#/%#.txt", documentsDirectory, #"file_name"];
NSData *orgData = [NSData dataWithContentsOfFile:file];
//Because there is only one char on my last line I make a range from 0 to length of data - 1 byte.
NSRange range = {0, [orgData length]-1};
NSData* shortData = [[NSData dataWithContentsOfFile:file] subdataWithRange:range];
[shortData writeToFile:file atomically:YES];
If you know a better way please let me know.

Pretty sure that this can be your solution:
NSFileHandle *file;
file = [NSFileHandle fileHandleForUpdatingAtPath:[self filePath]];
if (file == nil)
NSLog(#"Failed to open file");
//get the last character count
long long lastChar = [file seekToEndOfFile];
lastChar--;
lastChar--;
//from where do you want to remove
NSLog (#"Offset = %llu", lastChar);
//Move to position
[file seekToFileOffset: lastChar];
//write an empty string
[file writeData:[#" " dataUsingEncoding:NSUTF8StringEncoding]];
[file closeFile];

This is possibly okay, depending on the file.
Removing one character doesn't address thing like a trailing carriage return, so this may not actually work in practice. A better (more general) solution would be to load the file, and step backwards from the last character until you find the beginning of the last line (i.e. everything between the next-to-last carriage return and the final one), and then rewrite the file without the final line.

Related

write location / gps coordinates to a file

Well, I know it may sounds basic, but I have literally been looking everywhere and could not find a straight answer to that. I am trying to save location coordinates to a file every time I get an update - sounds simple.... I have two problems: one is with the data type (writeToFile seems to save only NSData) and the other one is with appending to the end of the file. I tried to use NSKeyedArchiver but it wrote a bunch of garbage and I could not find how to append to the end of file with it.
Here is my code - if you could help I would greatly appreciate that. Thanks!
....
NSMutableArray *array = [[NSMutableArray alloc] init];
NSNumber *numLat = [NSNumber numberWithFloat:location.coordinate.latitude];
NSNumber *numLong = [NSNumber numberWithFloat:location.coordinate.longitude];
[array addObject:numLat];
[array addObject:numLong];
NSFileHandle *file;
file = [NSFileHandle fileHandleForUpdatingAtPath: #"./location.txt"];
if (file == nil)
NSLog(#"Failed to open file");
[file seekToEndOfFile];
[file writeData: array]; //BTW - this line doesn't work if I replace array with numLat which is an NSNumber - unlike what many people have said in various discussions here
OR - for the saving to file portion (last two lines):
NSString *path = #"./location.txt";
[NSKeyedArchiver archiveRootObject:array toFile:path];
// Get the path to the Documents (this is where your app saves data)
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsPath = [searchPaths objectAtIndex: 0];
[array writeToFile:[documentsPath stringByAppendingPathComponent:#"location"] atomically:YES];
To load the data back into the array, use
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsPath = [searchPaths objectAtIndex: 0];
array = [[NSMutableArray alloc] initWithContentsOfFile:[documentsPath stringByAppendingPathComponent:#"location"];

can i generate a text file from my iphone application

Hi
I am creating a simple calculation based application and at end i need to create a text file for the calculation made in that app.Now i want that whole result into the text file, i dont if we can create a text file through our application or not but need to create that and also if we are able to create it then can we transfer to our pc/mac .
If any tutorial is available it would be of great help .
Regards
Mrugen
Try:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:#"myfile.conf"];
NSString *settings = #"1.0,0.0,0.0,0,";
NSData* settingsData;
settingsData = [settings dataUsingEncoding: NSASCIIStringEncoding];
if ([settingsData writeToFile:filePath atomically:YES])
NSLog(#"writeok");
Taken from: http://sio2interactive.forumotion.net/t347-how-to-write-a-text-file-to-iphone#1847

Saving a NSMutableArray into a txt-file / Loading txt-file back into NSMutableArray

I had a look around, trying to find a straightforward method for first saving a MutableArray (which will contain different text arrays from UITextViews with returns etc.) into a txt-file and then loading the txt-file back into my MutableArray.
I didn't manage to come up with the reverse method (loading the text-file) and was wondering how I should go about this. I'm sure txt files and mutable arrays are not really compatible, especially if I want the MutableArray to hold various text strings from UITextViews.
Is there a way to mark the beginning of one section in a mutable array and the beginning of the next in a txt file? The aim would be to be able to edit the txt file both in the program and in a simple text editor without messing up the structure of the mutable array.
Can I use a certain special character (not \n obviously) in my text file so as to separate different objects?
Here is what I've come up with so far. Sorry, I'm a beginner and it's very basic. The first problem is that I get the error message 'NSMutableArray' may not respond to '-writeToFile:atomically:encoding:error:'. Next, I have no idea how to load the txt back into my Array. Finally, I'd like to come up with a way to separate the arrays in the txt so that it remains editable, but that would be the absolute icing. Perhaps a solution would be to save each Object in an Array in a separate txt file and then load each txt into the array?
// GENERATE ARRAY
NoteBook = [[NSMutableArray alloc] init];
for (int temp = 0; temp < 3; temp++) {
[NoteBook insertObject:#"Title\n\n Line1\nLine2..." atIndex:temp];
}
// SAVING MY MUTABLE ARRAY
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSError *error;
BOOL succeed = [NoteBook writeToFile:[documentsDirectory stringByAppendingPathComponent:#"myfile.txt"]
atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
// Handle error here
}
// LOADING TEXTFILE AND PUT IT INTO A MUTABLE ARRAY
// NO IDEA... how to do this
Convert your arrays into strings, and vice versa, using, e.g.,
NSString* arrayText = [NoteBook componentsJoinedByString: #"<your-favourite-separator-string>"];
the write to file using [arrayText writeToFile...]
After reading a string back from a file, use
Notebook = [arrayText componentsSeparatedByString: #"<your-favourite-separator-string>"];
Lastly, don't do this. Save your array directly to a property list (read up on those) or JSON or some other structured data format.
Why not just turn the mutable array into JSON and write that string to a file? The inverse is to read the string from file and turn back into an array using the JSON parser. json-framework is very easy to use.
A benefit would be that you could create or modify your array by editing text files as long as you write valid JSON.
make NSMutableArray to NSArray .because NSMutableArray does not have writeToFile .
retriev array from file
NSArray *theCatalogInfo=nil;
NSString *theCatalogFilePath = [NSString stringWithFormat:#"%#/Documents/",NSHomeDirectory()];
theCatalogFilePath = [theCatalogFilePath stringByAppendingString:kCatalogCachePath];
if(nil!=theCatalogFilePath)
{
theCatalogInfo=[[NSArray alloc]initWithContentsOfFile:theCatalogFilePath];
}
Save array To file
NSString *theCatalogFilePath = [NSString stringWithFormat:#"%#/Documents/",NSHomeDirectory()];
theCatalogFilePath = [theCatalogFilePath stringByAppendingString:kCatalogCachePath];
[**YourArray** writeToFile:theCatalogFilePath atomically:YES];
Have a look at following three methods to create a text file, write to it and read the data from it.
The key is to store the different objects separated by space. And you should get it very simple.
-(void)createFile
{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Sample.txt"];
NSFileManager * file_manager = [NSFileManager defaultManager];
if(![file_manager fileExistsAtPath:filePath])
{
[file_manager createFileAtPath:filePath contents:nil attributes:nil];
NSString *content = #"NULL NULL NULL";
[content writeToFile:filePath
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
}
-(void)writeToFile
{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Sample.txt"];
NSString *content = [NSString stringWithFormat:#"%# %# %#", obj1, obj2, obj3];
[content writeToFile:filePath
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
-(void)readFromFile
{
objects = [[NSArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Sample.txt"];
if (filePath) {
NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSASCIIStringEncoding error:nil];
if (myText) {
objects = [myText componentsSeparatedByString:#" "];
}
}
}
if your nsarray contains nsdictionary, nsarray, nsstring, nsnumber, nsdata or nsdate objects (no custom objects, int's, etc) you can simply write the contents of your mutable array to a plist file.
this will maintain the data structure you have and you can simply read that data right into an array. How I do it in a couple of my data classes is
NSArray *tempArray = [NSArray arrayWithContentsOfFile:[Utils getFileLocation]];
if (tempArray == nil) {
yourArray = [[NSMutableArray alloc] init];
} else {
yourArray = [[NSArray deepMutableCopy:tempArray] retain];
}

How to load a txt file into an array

I coded a method to load a txt file into an array. However, I'm not really happy with it as it looks terribly cumbersome to my beginner's eyes (I'm sure I don't need 50% of my code) and I am somehow wondering how I can specify the exact format of my txt file, e.g. NSUTF8StringEncoding.
Here is my code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Sample.txt"];
if (filePath) { // check if file exists - if so load it:
NSString *myText = [NSString stringWithContentsOfFile:filePath];
if (myText) {textView.text=myText;}
}
For any suggestions of how to polish this up and specify the right format, I'd be very grateful.
Try the following, assuming your file is in your bundle:
NSString * filePath = [[NSBundle mainBundle] pathForResource:#"Sample" ofType:#"txt"];
NSError * error = nil;
NSString * contentsOfFile = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
Into an array? You mean into a string, since is exactly what you're doing...
However, your code looks not bad, and most of it is just to grab the documents directory path, and that's not your fault, since it's exactly done this way, according to many knowledge bases.
As of the encoding, stringWithContentsOfFile is deprecated, please use stringWithContentsOfFile:encoding:error: (see the docs)
and you will be able to specify the correct encoding and get accurate error descriptions.

Logging in a text file iPhone

I have a score system and I would like to log all scores in a text file separated by line breaks. Here is my current save code:
NSData *dataToWrite = [[NSString stringWithFormat:#"String to write ID:%i \n",random] dataUsingEncoding:NSUTF8StringEncoding];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [docsDirectory stringByAppendingPathComponent:#"text.txt"];
// Write the file
[dataToWrite writeToFile:path atomically:YES];
When retrieving this data, I only see the latest save. How do I make it so it saves all in a list?
Thanks.
[dataToWrite writeToFile:path atomically:YES]; overwrites the file at that location, replacing whatever is there with the contents of dataToWrite.
You can likely use NSFileHandle's fileHandleForWritingAtPath: and then call seekToEndOfFile to append to said file.
Do you have an example?
Try something like:
NSFileHandle *f = [NSFileHandle fileHandleForWritingAtPath: p];
[f seekToEndOfFile];
[f writeData: d];
[f close];
All typed into SO; the compiler/runtime might differ with my opinions of correctness.