How to read last n lines in a Text file in Objective C - ios

I have a Text file and it has lot of lines How can i get last 'n' number of lines from the text file? and Can we give Numbers in the text file for each file How can we get it.

You could use NSFileHandle, seekToEndOfFile and then work backwards from the offsetInFile using seekToFileOffset: and readDataOfLength: scanning the data read each time for carriage returns and counting them until you get to the required number. As you go you can build up the text after each scan.

One way is putting \n to separate your different lines in the text file. Then
NSString* path = [[NSBundle mainBundle] pathForResource:#"filename"
ofType:#"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSArray* lines = [content componentsSeparatedByString: #"\n"];
Then you can take the last few elements in the array.
Hope this helps..

Try to use this one:
NSString* textFile = [[NSBundle mainBundle]
pathForResource:#"fileName" ofType:#"txt"];
NSString* fileContents = [NSString stringWithContentsOfFile: textFile
encoding: NSUTF8StringEncoding error: nil];
Separate by new line
NSArray* allLinedStrings =
[fileContents componentsSeparatedByCharactersInSet:
[NSCharacterSet newlineCharacterSet]];
Here you can get your last 100 objects
NSString* oneLineStr;
for (int i = allLinedStrings.count - 100; i < allLinedStrings.count; i++)
{
oneLineStr = [allLinedStrings objectAtIndex: i];
NSLog#("New Line %#", oneLineStr);
}

Related

How do I create line breaks in a String I loaded from a textfile

I want to load a simple text, like:
"first \n second"
My code is :
NSString *filePath = [[NSBundle mainBundle] pathForResource:path ofType:#"df"];
NSArray* allLines;
if (filePath) {
NSString* content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
allLines = [content componentsSeparatedByString:#"#"]; //Of course my text is separate with #
}else{
NSLog(#"%# didnt load", path);
}
for (int i = 0; i < [allLines count]; i++) {
[_textArray addObject:(NSString*)allLines[i]];
NSLog(#"Answer: %#",(NSString*)allLines[i]);
}
And I want to get this text on an UILabel. But I don't know how I can make this line breaks to work. :S
Instead of putting \n in the text file, put actual newlines in the text file. In other words, put "first" and "second" on two separate lines in the text file.
You wanted either of
label.text = [allLines componentsJoinedByString:#"\n"];
label.text = [content stringByReplacingOccurrencesOfString:#"#" withString:#"\n"];
But yes, just putting the newlines in the source file works fine too.

How to read a text file ,turn it into a string, then using arguments on it

Say If I had a string = "There were %# apples,I ate %#. Now I have %# apples" in text file "Apples.txt". This is how I will extract the text from it.
NSString *path = [[NSBundle mainBundle] pathForResource:#"Apples" ofType:#"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
Now how do I pass the arguments to it so it looks like this:
"There were %# apples,I ate %#. Now I have %# apples", x, y, x-y
I am sure there is a way around this using NString with arguments? using
NSString with local argument functions? otherwise I will have to type all of my text in the file.m
This very crucial for my app.
You are probably looking for [NSString stringWithFormat:...].
Your complete code goes like this :
NSString *path = [[NSBundle mainBundle] pathForResource:#"Apples" ofType:#"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSNumber *total = #100;
NSNumber *ate = #34;
NSString *fullString = [NSString stringWithFormat:content,total,ate, #([total integerValue] - [ate integerValue])];
NSLog(#"%#", fullString);
Output:
"There were 100 apples,I ate 34. Now I have 66 apples".
Use + stringWithFormat:
Here's the Apple reference

Objective-C: Reading from a .rtf file into an array

I've looked around a bit and tried a few things, but none have really worked. What I'm trying to do is create a NSArray of NSStrings, with each array value corresponding to one line from the Rich Text File I'm referencing. At first I tried this:
NSArray* data = [[NSString stringWithContentsOfFile:#"relevantFile.rtf" encoding:4 error:nil] componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];
I've also tried this, because I found it in the iOS developer library:
NSArray* data = [[NSArray alloc] initWithContentsOfFile:#"relevantFile.rtf"];
However, neither of these has worked for me. A few lines later in the code, in order to diagnose errors, I have the following code:
for(int i = 0; i < [data count]; i++)
{
NSLog(#"%#", [data objectAtIndex: i]);
}
...for which NSLog is printing "(null)". I'm not entirely sure what I'm doing wrong here -- should I be using mutable strings or arrays, or is there some better way to go about this that I don't know about?
That first line you posted should do it. My guess would be that it's not finding the file. Not specifying an absolute path, the app will look in the current directory which is probably NOT where the file is.
If the file is a resource that is compiled into your app bundle, you can use the following code to obtain the path to it:
NSString* path = [[NSBundle mainBundle] pathForResource: #"relevantFile" ofType: #"rtf"]
NSArray* data = [[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil] componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];

editing occurrences is not working

i am trying to get the path to a certain file
and then open it in a webview. so i need to replace each space by '%20'
NSString *test=#"filename";
NSString *finalPath12 = [test stringByAppendingString:#".pdf"];
NSString *path1 = [[NSBundle mainBundle] bundlePath];
NSString *finalPath1 = [path1 stringByAppendingPathComponent:finalPath12];
NSString *file =#"file://";
NSString *htmlfilename1 = [file stringByAppendingString:finalPath1];
NSString *pathtofile = [htmlfilename1 stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
any string is working except #"%20".
this works perfectly for exemple:
NSString *pathtofile = [htmlfilename1 stringByReplacingOccurrencesOfString:#" " withString:#"string"];
but i need the #"%20". What am i missing ? Thanks
There is already [NSString stringByAddingPercentEscapesUsingEncoding:] (reference) for that very purpose.
However in your case, as you want a URL, you can replace all the lines in your question with:
NSURL *url = [[NSBundle mainBundle] urlForResource:#"filename" withExtension:#"pdf"];
You need to use #"%%20".
As first % is treated as escape/wild character.
Or use
stringByAddingPercentEscapesUsingEncoding:

Parsing and processing Text Strings in iOS

Wanted to find the best programming approach in iOS to manipulate and process text strings. Thanks!
Would like to take a file with strings to manipulate the characters similar to the following:
NQXB26JT1RKLP9VHarren Daggett B0BMAF00SSQ ME03B98TBAA8D
NBQB25KT1RKLP05Billison Whiner X0AMAF00UWE 8E21B98TBAF8W
...
...
...
Each string would process in series then loop to the next string, etc.
Strip out the name and the following strings:
Take the following 3 string fragments and convert to another number base. Have the code to process the new result but unsure of how to send these short strings to be processed in series.
QXB26
B0BM
BAA8
Then output the results to a file. The xxx represents the converted numbers.
xxxxxxxxx Harren Daggett xxxxxxxx xxxxxxxx
xxxxxxxxx Billison Whiner xxxxxxxx xxxxxxxx
...
...
...
The end result would be pulling parts of strings out of the first file and create a new file with the desired result.
There are several ways to accomplish what you are after, but if you want something simple and reasonably easy to debug, you could simply split up each record by the fixed position of each of the fields you have identified (the numbers, the name), then use a simple regular expression replace to condense the name and put it all back together.
For purposes like this I prefer a simple (and even a bit pedestrian) solution that is easy to follow and debug, so this example is not optimised:
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *URLs = [fm URLsForDirectory: NSDocumentDirectory
inDomains: NSUserDomainMask];
NSURL *workingdirURL = URLs.lastObject;
NSURL *inputFileURL = [workingdirURL URLByAppendingPathComponent:#"input.txt" isDirectory:NO];
NSURL *outputFileURL = [workingdirURL URLByAppendingPathComponent:#"output.txt" isDirectory:NO];
// For the purpose of this example, just read it all in one chunk
NSError *error;
NSString *stringFromFileAtURL = [[NSString alloc]
initWithContentsOfURL:inputFileURL
encoding:NSUTF8StringEncoding
error:&error];
if ( !stringFromFileAtURL) {
// Error, do something more intelligent that just returning
return;
}
NSArray *records = [stringFromFileAtURL componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];
NSMutableArray *newRecords = [NSMutableArray array];
for (NSString *record in records) {
NSString *firstNumberString = [record substringWithRange:NSMakeRange(1, 5)];
NSString *nameString = [record substringWithRange:NSMakeRange(15, 27)];
NSString *secondNumberString = [record substringWithRange:NSMakeRange(43, 4)];
NSString *thirdNumberString = [record substringWithRange:NSMakeRange(65, 4)];
NSString *condensedNameString = [nameString stringByReplacingOccurrencesOfString:#" +"
withString:#" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, nameString.length)];
NSString *newRecord = [NSString stringWithFormat: #"%# %# %# %#",
convertNumberString(firstNumberString),
condensedNameString,
convertNumberString(secondNumberString),
convertNumberString(thirdNumberString) ];
[newRecords addObject: newRecord];
}
NSString *outputString = [newRecords componentsJoinedByString:#"\n"];
[outputString writeToURL: outputFileURL
atomically: YES
encoding: NSUTF8StringEncoding
error: &error];
In this example convertNumberString is a plain C function that converts your number strings. It could of course also be a method, depending on the architecture or your preferences.

Resources