Sandy
Sandy

Reputation: 353

Convert contents of a file into NSString

I want to read the contents of files of any type which will be opened in my app from anywhere and convert the content to NSString and then convert this string to hex and ASCII. I have used the following code to read the contents of rtf file but its returning me some absurd values.

NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filepath = [[path objectAtIndex:0]stringByAppendingPathComponent:@"/Inbox"];
NSString *filepath1 = [filepath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@",fileName]];
NSString *contents = [NSString stringWithContentsOfFile:filepath1 encoding:NSUTF8StringEncoding error:&error];
NSLog(@"%@",contents);

The contents of the rtf file were : This is a test document to chi the hex view. And the response i got is :

\rtf1\ansi\ansicpg1252\cocoartf1187\cocoasubrtf340
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural

\f0\fs24 \cf0 is a test document to chi the hex view.

I need to read the content of any type of file except for zip and rar. Please help....

Upvotes: 3

Views: 5174

Answers (1)

sangony
sangony

Reputation: 11696

If you are looking to read a text file then you can try something like this:

NSString* path = [[NSBundle mainBundle] pathForResource:@"test"
                                                 ofType:@"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
                                              encoding:NSUTF8StringEncoding
                                                  error:NULL];

For a more detailed look, I suggest you read the NSString Class Reference section 'Creating and Initializing a String from a File'.

Upvotes: 2

Related Questions