I have a text file with a single floating number in it that needs to be opened and read as a floating value so I can use it in my equations. I have successfully read in the text file as a string and checked it in UITextView to make sure the file was in the correct path etc. Below is how I am reading the file and I have tried using an NSScanner to read the number as a float but cannot get it to work.
NSString *filePath2 = [[NSBundle mainBundle] pathForResource: #"time" ofType: #"txt"];
NSString *textFromFile = [NSString stringWithContentsOfFile:filePath];
// i know the above won't work because it reads the file as a string
Use
[textFromFile doubleValue];
Related
I am very new to Objective C and I've been searching Google for a number of hours trying to find a solution.
I have an NSString which looks like
273350/364D4D002A00041EB8F1E0CEF1E0CCF1E0CCF1E0CCF1E0CCF etc etc
which refers to a TIFF image (I guess in some sort of RAW string format), I want to populate an NSImageView with the data.
This is what I've attempted so far:
NSData *picdata = [NSData dataWithBytes:[albumArtStr UTF8String] length:[albumArtStr length]];
NSImage *myPicture = [[NSImage alloc] initWithData:picdata];
[_albumArtCell setImage:myPicture];
Where "albumArtCell" is the NSImageView
That data looks like hex encoded image with a length in front of it, not an unencoded TIFF, which is a tagged binary format. Perhaps you need to strip the number before the slash and decode e rest of the string from hex digits into NSData and then call [[NSImage alloc] initWithData] using that decided data.
You will need to decode it to binary before handing it to NSImage as it only understands the raw binary form of TIFF.
I believe the problem is due to the fact that [albumArtStr length] returns the number of "unicode character", and not number of "bytes".
So your NSData is probably not set-up to be the right size and so doesn't have the right format for a UIImage to be decoded properly.
Try this instead to create a NSData from NSString instance:
NSData* picData = [albumArtStr dataUsingEncoding: NSUTF8StringEncoding];
I was surfing on the Net a lot, but still I haven't found an answer to my question: how to write variables to a .txt file and what's the best way to write NSStrings to .txt files. I've tried using writeToFile method, but if I have two calls of this method, then the text that was written when the first one was called will be overwritten. I want to have a kind of history of what has happened, and values of some variables in my .txt file. How should I do it?
If you just want to append a string to a .txt file, you could do this:
NSString *string = ...; // your string
NSString *path = ...; // path to your .txt file
// Open output file in append mode:
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:path append:YES];
[stream open];
// Make NSData object from string:
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
// Write data to output file:
[stream write:data.bytes maxLength:data.length]; // XXX
[stream close];
Remark: If this is in an .mm file and therefore compiled as Objective-C++, then the second to last line (marked with XXX) must be replaced by
[stream write:static_cast<const uint8_t *>(data.bytes) maxLength:data.length];
because C++ requires an explicit cast from const void * to const uint8_t *.
I need to parse a FILE URL in my application, and replace the %20 for a SPACE. I am using stringByReplacingOccurance:
NSString *strippedContent = [finalFilePath stringByReplacingOccurrencesOfString:#"%20" withString:#" "];
But when I display strippedContent in an NSLog, all of the %20 strings are still there. Here is an example of the file name I hope to parse:
.../Documents/Inbox/Test%20Doc%20From%20Another%20App.txt
It seems as if NSFileManager cannot find the document when it has the %20 in it.
The file path is being passed from another application through the "Open In..." dialogue. Is there any way to remove the %20 with stringByReplacingOccurrence or when the URL is imported?
NSString provides a method that performs the conversion that you need:
NSString *strippedContent = [finalFilePath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Yes you should use:
NSString * strippedContent = [finalFilePath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
I am trying to create a file by fopen and then write it, but weird things happened.
When I plug in the iphone to the usb port. Everything works fine. A file is created at the tmp directory or the document directory as expected.
When I plug off the device and do the same thing, the file did not appear. I was wondering why.
I use fopen to create the file. In my case, I should do this to create and then write the file. The call is fopen(pcm_output, "wb+");
You need to use this call.
char const *path = [fileManager fileSystemRepresentationWithPath:url.path];
From the docs...
fileSystemRepresentationWithPath:
- (const char *)fileSystemRepresentationWithPath:(NSString *)path
iOS (2.0 and later)
Returns a C-string representation of a given path that properly encodes Unicode strings for use by the file system.
path: A string object containing a path to a file.
A C-string representation of path that properly encodes Unicode strings for use by the file system.
You're probably writing outside of the sandbox, can you post the path?
Just as a test try to turn on iTunes Sharing (this should have no effect, it's just a test) for your app.
EDIT:
After testing I discovered that you have to use:
NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [docsPath stringByAppendingPathComponent:[NSString stringWithCString:pcm_output encoding:NSUTF8StringEncoding]];
fopen([filePath UTF8String], "wb+");
Instead of just:
fopen([filePath UTF8String], "wb+");
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,
NSUserDomainMask, YES
);
NSString* docDir = [paths objectAtIndex:0];
_tempLogPath = [docDir stringByAppendingPathComponent: #"Aisound5_CBLog.log"];
_tempPcmPath = [docDir stringByAppendingPathComponent: #"OutPcm.pcm"];
_tempWavPath = [docDir stringByAppendingPathComponent: #"OutWav.wav"];
tts_resource = [[bundle pathForResource:#"Resource_dev" ofType:#"irf"] UTF8String];
tts_log = [_tempLogPath UTF8String];
pcm_output = [_tempPcmPath UTF8String];
wav_output = [_tempWavPath UTF8String];
The original code is this, in which tts_resource tts_log pcm_output and wav_output are defined in a .h file and used in a .c file with fopen.
I had tried in your way to init the const string with the explicit const char* style, but the problem remains the same.
I have a file, which I'm reading into an NSString object using stringWithContentsOfFile. It contains Unicode for Japanese characters such as:
\u305b\u3044\u3075\u304f
which I believe is
せいふく
I would like my NSString object to store the string as the latter, but it is storing it as the former.
The thing I don't quite understand is that when I do this:
NSString *myString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
It stores it as: \u305b\u3044\u3075\u304f.
But when I hardcode in the string:
NSString *myString = #"\u305b\u3044\u3075\u304f";
It correctly converts it and stores it as: せいふく
Does stringWIthContentsOfFile escape the Unicode in some way? Any help will be appreciated.
Thanks.
In the file \u305b\u3044\u3075\u304f are just normal characters. So you are getting them in string. You need to save actual Japanese characters in the file. That is, store せいふく in file and that will be loaded in the string.
You can try this, dont know how feasible it is..
NSArray *unicodeArray = [stringFromFile componentsSeparatedByString:#"\\u"];
NSMutableString *finalString = [[NSMutableString alloc] initWithString:#""];
for (NSString *unicodeString in unicodeArray) {
if (![unicodeString isEqualToString:#""]) {
unichar codeValue;
[[NSScanner scannerWithString:unicodeString] scanHexInt:&codeValue];
NSString* betaString = [NSString stringWithCharacters:&codeValue length:1];
[finalString appendString:betaString];
}
}
//finalString should have せいふく
Something like \u305b in an Objective-C string is in fact an instruction to the compiler to replace it with the actual UTF-8 byte sequence for that character. The method reading the file is not a compiler, and only reads the bytes it finds. So to get that character (officially called "code point"), your file must contain the actual UTF-8 byte sequence for that character, and not the symbolic representation \u305b.
It's a bit like \x43. This is, in your source code, four characters, but it is replaced by one byte with value 0x43. So if you write #"\x43" to a file, the file will not contain the four characters '\', 'x', '4', '3', it will contain the single character 'C' (which has ASCII value 0x43).