iphone scanning a dat file for data - iphone

I am trying to remake a program I have made in C# in OBJ-C.In C# I used streamreader to search the data file for the line I am looking for then convert that line into a string that I can work with.
I have looked at NSScanner but I'm not sure if thats quite waht I'm looking for but I'm by no means a cocoa expert.
All I would like to be able to do is have it search a data file for an occurance of a string, then when/if it finds an occurance of that string, it returns the line that string was found on as a string.
Any ideas?

If your data file isn't to large to fit in memory, you can just load it into a string and search it using string methods. For example:
NSData *data = [NSData dataWithContentsOfFile:#"/path/to/file.dat"];
NSString *dataString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
for (NSString *line in [dataString componentsSeparatedByString:#"\n"])
if (!NSEqualRanges([line rangeOfString:searchString], NSMakeRange(NSNotFound,0)))
return line;

Related

NSString stringWithContentsOfFile:fileName non-english letters

I have a file with many lines separated by "\n". One of the lines is:
Christian Grundekjøn
I can't read the file unless I delete the line. I use the following code to read line by line:
for (NSString *line in [[NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:NULL] componentsSeparatedByString:#"\n"])
If I don't delete the line, the code wouldn't even go into the for loop at all. Nothing was read. How to handle the non-English letters?
If you are generating the text file from within iOS then you need to make sure you are encoding it with NSUTF8StringEncoding. But given the problem you are reporting, I suspect that you may be pulling in data from another source and that source hasn't encoded the text as UTF8. If this is the case, you may be able to fix the problem outside your app but converting the source file to UTF8.
If you don't know what encoding is used, e.g. because the user has supplied the file, iOS can try to guess it for you. A pattern that I have used successfully is to first try to get the string using UTF8 encoding, for example using the same approach you use. Assuming you write a method, to which you pass a filename, to get the string something like the following:
- (NSString*) stringFromFile: (NSString*) filePath;
{
NSError* error = nil;
NSString* stringFromFile = [NSString stringWithContentsOfFile: fileName
encoding: NSUTF8StringEncoding
error: &error];
if (stringFromFile) return stringFromFile; // success
NSLog(#"String is not UTF8 encoded. Error: %#", [error localizedDescription]);
NSStringEncoding encoding = 0;
NSError* usedEncodingError = nil;
NSString* stringFromFile = [NSString stringWithContentsOfFile: path
usedEncoding: &encoding
error: &usedEncodingError];
if (stringFromFile)
{
NSLog(#"Retrieved string using an alternative encoding. Encoding was: %d", encoding);
return stringFromFile;
}
// either handle error or attempt further explicit unencodings here
return nil;
}
In many cases, usedEncoding works very well. But there are edge cases where trying to figure out an encoding can be very tricky. It all depends on the source file.
I had problem with Japanese characters. My solution was when saving file to doc directory
NSString *fileData = [NSString stringWithFormat:#"%#", noteContent];
BOOL isWriteToFile = [fileData writeToFile:notePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
When reading file content
[[NSString alloc] initWithContentsOfFile:fullNotePath usedEncoding:nil error:nil];
In the file, store your data in unicode format or you can also store special character in unicode format.

creating a binary (.bin) file and read values from file in iphone

Hi i am trying to save text values as binary file and read from that file. i am using following code, i got the binary file in documents directory but when reading data from file only got some numbers please kindly help its urgent.
For writing
NSString *documentsDirectoryPath = [self performSelector:#selector(tempDirectoryPath:) withObject:fileName_];
NSLog(#"%#",documentsDirectoryPath);
if ([[NSFileManager defaultManager] isWritableFileAtPath:documentsDirectoryPath]) {
NSLog(#"content =%#",data_);
[data_ writeToFile:documentsDirectoryPath atomically:YES];
return YES;
}
For reading i use the following code,
NSString *documentsDirectoryPath = [self performSelector:#selector(tempDirectoryPath:) withObject:fileName_];
if ([[NSFileManager defaultManager] isReadableFileAtPath:documentsDirectoryPath]) {
NSMutableData *data_ = [NSMutableData dataWithContentsOfFile:documentsDirectoryPath];
return data_;
}
I got only numbers from the data_ .
How to read the .bin file correctly.?
I got the .bin file when extract get .bin.cpgz file.I can't open the file what is the reason ?Is anything wrong in code?
I am pass string in this way:
[self writeData:#"test string is here" toFile:#"mf.bin"];
Thanks.
It's a little late, but something like this might help you:
http://snippets.aktagon.com/snippets/475-How-to-use-NSKeyedArchiver-to-store-user-settings-on-the-iPhone
Sounds like you need to convert the data into something readable.
NSString *myFile = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
This assumes originally the data you wrote was a NSString, if it was an object you would have to use the appropriate methods for that object.

Non-English Characters in JSON

I'm using a JSON file which contains non-English characters.Hence when I'm fetching values from this file, it is showing some Chinese like characters in the simulator.In the console, I'm getting values like
\U2021\U00c6\U00e1\U2021\U00c6\U00a9\U2021\U00d8\U00e7\U2021\U00c6\U00b1\U2021\U00d8
\U00e0\U2021\U00c6\U00d8\U2021\U00c6\U00d6\U2021\U00c6\U2264\U2021\U00c6\U2122\U2021
\U00d8\U00e7\U2021\U00c6\U2122\U2021\U00c6\U00b1\U2021\U00d8\U00e0\U2021\U00c6\U00ef
\U2021\U00d8\U00e7 \U2021\U00c6\U00ef\U2021\U00d8\U00c7\U2021\U00c6\U00fc...
Any idea?
Try to print in such way:
NSString *currentString = [[[NSString alloc] initWithData:characterBuffer encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"Converted string: %#", currentString);
where characterBuffer is buffer where you've collected received data, replace NSUTF8StringEncoding with appropriate encoding, used at your server.

How i can use stringWithContentOfFile while text is not UTF8 format

I have many files html type. Now i want to get content of them. But the text is not UTF8 format so stringWithContentOfFile function return nil. The problem is i can't convert text of file to UTF8 because there are many files. I tried use WebView but not success. There are any way to read files?
Get the data using dataWithContentsOfFile: method and then convert it into an NSString object using initWithData:encoding: method. You can provide the encoding there.
NSData * data = [NSData dataWithContentsOfFile:filePath];
NSString * fileInString = [[NSString alloc] initWithData:data encoding:yourEncoding];

Parsing NSStrings to ensure a correctly formed JSON string within XCode

I am reading string data from a PLIST which I am using to create a JSON string (incidentally for use within Facebook Connect).
NSString *eventLink = [eventDictionary objectForKey:EVENT_FIND_OUT_MORE_KEY];
NSString *eventLinkEscaped = [eventLink stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *eventName = [eventDictionary objectForKey:EVENT_NAME_KEY];
NSString *eventDescription = [eventDictionary objectForKey:#"Description"];
NSString *eventImageAddress = [eventDictionary valueForKey:#"Image URL"];
if ([eventImageAddress length] == 0)
{
eventImageAddress = NO_EVENT_IMAGE_URL;
}
// Publish a story to the feed using the feed dialog
FBStreamDialog *facebookStreamDialog = [[[FBStreamDialog alloc] init] autorelease];
facebookStreamDialog.delegate = self;
facebookStreamDialog.userMessagePrompt = #"Publish to Facebook";
facebookStreamDialog.attachment =[NSString stringWithFormat: #"{\"name\":\"%#\",\"href\":\"%#\",\"description\":\"%#\",\"media\":[{\"type\":\"image\",\"src\":\"%#\",\"href\":\"%#\"}]}", eventName, eventLinkEscaped, eventDescription, eventImageAddress, eventLinkEscaped];
[facebookStreamDialog show];
All this works well, but certain event descriptions (4 out of approx. 150) the text that appears in the dialog is blank. I have found the obvious candidates, i.e., the description contains the " character for instance or the copyright symbol. My question is, is there an easy method call, such as stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding that will ensure that any dodgy characters are escaped or ignored?
Thanks in advance,
Dave
I don't think there is an easy way to escape the problem strings. If you need JSON support anywhere else in your code, consider using one of the existing JSON parsing/generator frameworks such as yajl-objc or SBJSON. Either of these will let you build your response as Foundation objects (NSArray/NSDictionary) and then call a single method to generate the appropriate JSON. Your code will be cleaner and you have the benefit that both of these frameworks are well-tested.
If just need to generate this one bit of JSON, your best bet is probably to manually walk over the input strings, replacing potential problem characters with the appropriately escaped versions. Is is not as bad as you might think. Take a look at the source for SBJsonWriter