Question regarding to reading a file in UTF8 encoding...

Discussion in 'Mac Programming' started by msharp, Jun 26, 2009.

  1. msharp macrumors regular


    Jul 10, 2004
    Hi there,

    I've been really struggling against a very simple (seems to be) issue in the past 48 hours, so I guess I should ask for some tips here.

    Here's the thing: I wanted to read a file using utf-8 encoding, and save the file content as a NSString. Here's my code:
    DBPath = [NSString stringWithUTF8String:[[NSData dataWithContentsOfFile:filePath] bytes]];
    Well, it can perfectly run without any warnings/errors, BUT it always produces a few more characters to the file content in the NSString.

    For example, the file content may be: "/Users/myname/Document.doc", but the NSString seems to be "/Users/myname/Document.docame/Library/P" or something like that.

    Some times, the NSString is simply "/Users/myname/Document.doc?" (with a question mark added to the end of the string).

    So, could anyone give me some hint for this issue?

    Thanks a lot in advance!
  2. rossipoo macrumors regular

    Jun 7, 2009
    Try it like this
    NSString *DBString = [NSString stringWithContentsOfFile: filePath
    					       encoding: NSUTF8StringEncoding
    						  error: nil];

Share This Page