Basically i have a concern, which needs to be solved using Objective C alone. (i have tried with C)
Is there any appropriate way in objective C to read character by character (till EOF) from a file, The file is got from document directory or bundle.
Problem : So, If i want to append a escape character () before all inverted comma's in a file and A special character (say /) before each line.
Replace
(type == "Currency")
with
/(type == \"Currency\")
Thanks in advance.
Try this may be this helps you.
I assume your file contains only string data not JSON or XML
NSString *strFileContent = [NSString stringWithContentsOfFile:#"pathofyourfile" encoding:NSUTF8StringEncoding error:nil];
NSLog(#"strFileContent %#",strFileContent);
NSString *newStr = [strFileContent stringByReplacingOccurrencesOfString:#"(" withString:#"/("];
Like last line you can replace your data.
Hope this works for you.
Related
I want to insert a unicode symbol for pi, which is \u03c0 into a label and for it to display the symbol. I am loading this in from an array which was read from a txt file. For example if I have a txt file that contains "\u03c0":
string = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]
array[i] = string;
label.text = array[i];
What am getting is "\u03c0" as an output in the textfield, but I want the symbol. What I am doing wrong?
Edit: it seems that my problems is with string encoding because I am reading in the array from a file. I was using NSUTF8StringEncoding. What should this be changed to to allow unicode?
My guess is the contents of your file contains \\u03c0 rather than the actual character. If you have control of the file contents, paste in the actual character, not the sequence, because the editor will save it with the escaping "\". If you don't have control, i suggest writing code to detect this escaping, strip the preceding "\" and then use the result in your format.
Say I have text file my.txt like this
this is line 1
this is line 2
....
this is line 999999
this is line 1000000
In Unix I can get the line of "this is line 1000" by issuing command like "head -1000 my.txt | tail -1". What is the corresponding way to get this in Objective-C?
If it's not too inefficient to have the whole thing in memory at once then the most compact sequence of calls (which I've expanded onto multiple lines for simpler exposition) would be:
NSError *error = nil;
NSString *sourceString = [NSString stringWithContentsOfFile:#"..."
encoding:NSUTF8StringEncoding error:&error];
NSArray *lines = [sourceString componentsSeparatedByCharactersInSet:
[NSCharacterSet newlineCharacterSet]];
NSString *relevantLine = [lines objectAtIndex:1000];
You should check the value of error and the count of lines for validation.
EDIT: to compare to Nathan's answer, the benefit of splitting by characters in set is that you'll accept any of the five unicode characters that can possibly delimit a line break, with anywhere where several of them sit next to each other counting as only one break (as per e.g. \r\n).
NSInputStream is probably what you're going to have to deal with if memory footprint is an issue, which is barely more evolved than C's stdio.h fopen/fread/etc so you're going to have to write your own little loop to dash through.
The answer does not explain how to read a file too LARGE to keep in memory. There is not nice solution in Objective-C for reading large text files without putting them into memory (which isn't always an option).
In these case I like to use the c methods:
FILE* file = fopen("path to my file", "r");
size_t length;
char *cLine = fgetln(file,&length);
while (length>0) {
char str[length+1];
strncpy(str, cLine, length);
str[length] = '\0';
NSString *line = [NSString stringWithFormat:#"%s",str];
% Do what you want here.
cLine = fgetln(file,&length);
}
Note that fgetln will not keep your newline character. Also, We +1 the length of the str because we want to make space for the NULL termination.
The simplest is to just load the file using one of the NSString file methods and then use the -[NSString componentsSeparatedByString:] method to get an array of every line.
Or you could use NSScanner, scan for newline/carriage return characters counting them until you get to you line of interest.
If you are really concerned about memory usage you could look at NSInputStream use that to read in the file, keeping count of the number of newlines. It a shame that NSScanner doesn't work with NSInputStream.
I don't think this is an exact duplicate, because it sounds like you want to skip some lines in the file, but you could easily use an approach like the one here:
Objective-C: Reading a file line by line (Specific answer that has some sample code)
Loop on the input file, reading in a chunk of data, and look for newlines. Count them up and when you hit the right number, output the data after that one and until the next.
Your example looks like you might have hundreds of thousands of lines, so definitely don't just read in the file into a NSString, and definitely don't convert it to an NSArray.
If you want to do it the fancier NSInputStream way (which has some key advantages in character set decoding), here is a great example that shows the basic idea of polling to consume all of the data from a stream source (in a file example, its somewhat overkill). Its for output, but the idea is fine for input too:
Polling versus Run Loop Scheduling
Does anyone know if this line of code would work for a NSString from an rtf file on iOS?
NSString* cList = [[NSString alloc] initWithContentsOfFile:#"name of file" encoding:NSUTF8StringEncoding error:nil];
c = [cList componentsSeparatedByString:#"\n• "];
I'm just wondering since it includes a bullet point character which I pretty much copy pasted. I wasn't expecting it to be that easy. It just seems like it should be an escape sequence character or something.
Probably should've included some form of error checking in the first line, but that aside for the moment.
Update: After much compiling with no success with an rtf, I copied the text into a txt and used that instead. Works the first time. Seemed like the rtf reading was getting weird rtf data that wasn't really what I was after when I tried to NSLog it.
Thanks!
How about using unicode sequence?
like...
c = [cList componentsSeparatedByString:#"\n\u0000 "];
0000 <---- unicode.
I want to use NSFileHandle to write large text files to avoid handling very large NSString's in memory. I'm having a problem where after creating the file and opening it in the Text Edit app (Mac), it is not displaying the unicode characters correctly. If I write the same text to a file using the NSString writeToFile:atomically:encoding:error: method, Text Edit display everything correctly.
I'm opening both the files in Text Edit with the "opening files encoding" option set to automatic, so I'm not sure why one works and the other method doesn't. Is there some form of header to declare the format is UTF8?
// Standard string
NSString *myString = #"This is a test with a star character \u272d";
// This works fine
// Displays: "This is a test with a star character ✭" in Text Edit
[myString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding];
// This doesn't work
// Displays: "This is a test with a star character ‚ú≠" in Text Edit
[fileManager createFileAtPath:path contents:nil attributes:nil];
fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
[fileHandle writeData:[myString dataUsingEncoding:NSUTF8StringEncoding]];
The problem is not with your code, but with TextEdit: It doesn't try to decode the file as UTF-8 unless it has a UTF-8 BOM identifying it as such. Presumably, the first version of your code adds such a BOM. See this question for further discussion.
UTF-8 data generally should not include a BOM, so you probably shouldn't modify your code from the second version at all—it's working correctly. If opening the file in TextEdit has to work, you should be able to force the BOM by including it (\ufeff) explicitly at the start of the string, but, again, you should not do that unless you really need to.
I am parsing a tab seperated list using a NSScanner based upon each line and the tabs. However for some reason the last field in the array (parsed from each row) contains a \r character.
How can I strip this from the NSString that represents the line (or the field)
If the \r character is at the end (probably because the file being parsed is CRLF), you can just do something like [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]. (You might want to use an explicitly created '\r' character set instead if you don't want to strip whitespace as well.)
Try using the +[NSCharacterSet newlineCharacterSet] method with NSScanner in your various scanning method calls.
Just FYI, The \r is part of the line ending for a file created in a windows environment.