How do I parse a text file in Objective-C? - iphone

I need to parse a text file, one line at a time. Also, is there EOF in Objective-C?

Something like this might work for you:
NSString *fileContents = [NSString stringWithContentsOfFile:#"myfile.txt"];
NSArray *lines = [fileContents componentsSeparatedByString:#"\n"];
This will give you an array where each element is a line of the string.

Objective-C is a proper extension of C. Any C program is a valid Objective-C program. Among other things, this means that EOF defined in the standard C header "stdio.h" is an EOF marker in Objective-C as well.

stringWithContentsOfFile is deprecated.
Here is an updated answer:
NSError* error;
NSString *fileContent = [NSString stringWithContentsOfFile:txtFilePath encoding:NSUTF8StringEncoding error:&error];
NSArray *lines = [fileContent componentsSeparatedByString:#"\n"];

Related

How to encode URL in objective c xcode?

I'm doing this to encode my URL in this way,
but its not working,
i got the result in NSLog but its the same url nothing is changing.
Please help me to sort this issue.
below is my code :
NSString *unencodedUrlString =
[#"http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2,7"
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#" %#", unencodedUrlString);
Thanks in advance
The comma is a legal URL character, therefore stringByAddingPercentEscapesUsingEncoding leaves "2,7" as it is and does not replace it by "2%2C7".
If you want the comma to be replaced by a percent escape (as I understand from your
comment to the question), you can use CFURLCreateStringByAddingPercentEscapes
instead:
NSString *str = #"http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2,7";
NSString *encoded = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(__bridge CFStringRef)(str), NULL, CFSTR(","), kCFStringEncodingUTF8));
NSLog(#"%#", encoded);
Output:
http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2%2C7
The fourth parameter CFSTR(",") specifies that the comma should be replaced by
a percent escape even if it is a legal URL character.
Use this
NSString *str = [NSString stringWithFormat:#"http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2,7"];
NSString *path = [str stringByReplacingOccurrencesOfString:#"," withString:#"/"];
NSLog(#"%#",path);
This will do nothing but will make , to /.

Special characters xml parsing issue in iphone

When i try to parse xml containing email address say john#abc.com, it just shows "abc.com".
How can i make it to show the complete email address. In other cases i've removed some special charcters by using the following:-
string=[string stringByReplacingOccurrencesOfString:#"$" withString:#""];
but here i've to include the symbol "#" and characters before it.
Thanks for any help.
Well... finally found a solution for myself. I converted the xml data into a string and replaced characters. Below is the code:-
NSError* error;
NSString *content = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
content=[content stringByReplacingOccurrencesOfString:#"#" withString:#"#"];
NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
Problem Solved :)
NSString *string = #"$amdocs.com";
string=[string stringByReplacingOccurrencesOfString:#"$" withString:#"#"];
NSLog(#"%#",string);
maybe it will help you.

Can not read file in XCODE 4.2, worked in 4.0?

I have upgraded from XCODE 4 to 4.2 and now i have problems.
The following code worked pre 4.2 to read the file in "filePath":
// Fill myString with questions from the .txt file and then read .txt file
NSString *filePath = whatFile;
NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath];
// Load array
NSArray* myArray = [myString componentsSeparatedByString:#"\r"];
NSLog (#"\n \n Number of elements in myArray = %i", [myArray count]);
With 4.2 the "initWithContentsOfFile" in the following code line is deprecated:
NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath];
...and should be replaced with the below according to the manual:
NSString *myString = [NSString stringWithContentsOfFile:filePath encoding: NSUTF8StringEncoding error:&err];
and i can not get this to read the records in the same file by replacing the code line. BTW, i have defined the &err.
When i NSLog myString i get (null).
I am getting a bit desperate to solve this and would very much appreciate any help.
Cheers
NSLog the err variable if there is an error. Also NSLog filePath.
Perhaps the encoding is not UTF-8, are you sure about the encoding?
The best non-UTF-8 encoding bet is NSMacOSRomanStringEncoding which supports 8-bit characters.
Try :
NSError* error = nil;
NSStringEncoding encoding;
NSString *fileContent = [NSString stringWithContentsOfFile:filePath usedEncoding:&encoding error:&error];
If that does not works, try in your code : NSASCIIStringEncoding
The file probably doesn't contain a UTF8 encoded string. See apple's documentation, which has an example of reading a file where you do not know the encoding: Reading data with an unknown encoding
You need to use the [string|init]WithContentsOfFile:usedEncoding:error method, and if that fails there are a few more things you can try before finally presenting an error message to the user (for example, try reading it as an NSAttributedString).
For example, you could do this:
// Fill myString with questions from the .txt file and then read .txt file
NSString *filePath = whatFile;
NSStringEncoding encoding;
NSError *error;
NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath usedEncoding:&encoding error:&error];
if (!myString) {
myString = [[NSString alloc] encoding:NSUTF8StringEncoding error:&error]
}
if (!myString) {
myString = [[NSString alloc] encoding:NSISOLatin1StringEncoding error:&error]
}
if (!myString) {
NSLog(#"error: %#", error);
return;
}
// Load array
NSArray* myArray = [myString componentsSeparatedByString:#"\r"];
NSLog (#"\n \n Number of elements in myArray = %i", [myArray count]);

Add data to NSMutableArray from a text file separated by line break?

I have a txt file with some URLs like this
http://url1.com
http://url1.com
http://url1.com
Separated by a line break. How could I add those as different entries separated by line breaks to an NSMutableArray? Thanks :)
Try something like this:
NSMutableArray *txtLines = [NSMutableArray array];
[txtFile enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) {
if ([line length] > 0) {
[txtLines addObject:line];
}
}];
Update
#Evan is right, the above only works if blocks are available on your platform. A compiler directive around that code should take care of this limitation, e.g.:
#if NS_BLOCKS_AVAILABLE
// iOS 4.0+ solution
#else
// iOS 2.0+ solution
#endif
NSString *myListString = /* load / download file */
NSMutableArray *myList = [myListString componentsSeparatedByString:#"\n"];
You may have to use <br/> if it's HTML.
#octy's solution is only available in iOS 4.0 or later. This solution is iOS 2.0 or later. You can check the iOS version and choose which one to use:
BOOL useEnumeratedLineParsing = FALSE;
NSString *reqSysVer = #"4.0";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
useEnumeratedLineParsing = TRUE;
Then check the value of useEnumeratedLineParsing.
NSString *textFilePath = [[NSBundle mainBundle] pathForResource:#"urls" ofType:#"txt"];
NSString *fileContentsUrls = [NSString stringWithContentsOfFile:textFilePath encoding:NSUTF8StringEncoding error:nil];
NSArray *myArray = [urls componentsSeparatedByString:#"\n"];
As long as it isn't mega-large, you could read the whole file into an NSString.
NSString *text = [NSString stringWithContentsOfFile:path encoding:NSUTF8Encoding error:nil];
Then split the lines:
NSArray *lines = [text componentsSeparatedByString:#"\n"];
And make it mutable:
NSMutableArray *mutableLines = [lines mutableCopy];
Now, depending on where your text file is coming from, you probably need to be more careful. It could be separated by \r\n instead of just \n, in which case your lines will contain a bunch of extra \r characters. You could clean this up after the fact, using something to remove extra whitespace (your file also might have blank lines which the above will turn into empty strings).
On the other hand, if you're in control of the file, you won't have to worry about that. (But in that case, why not read a plist instead parsing a plain text file...)

using NSString + stringWithContentsOfFile:usedEncoding:error:

I've got problem with use + stringWithContentsOfFile:usedEncoding:error:
My problem in usedEncoding:(NSStringEncoding *)enc
I don't know how can i set pointer to encoding. If i make it - programm is fail.
For example, in similar function we have encoding:(NSStringEncoding)enc - without pointer!
I want loading file (file has encoding ISOLatin1) in NSString and use NSString as UTF8String.
how can i make it ?
thanks.
NSStringEncoding encoding;
NSError* error;
NSString* myString = [NSString stringWithContentsOfFile:myFilePath usedEncoding:&encoding error:&error];