Read a text file with Core Foundation in Apple development?

what is the easiest, most straight-forward method to read a text file and copy it into a variable (CFStringRef)?

Answers


If you're simply looking to end up with a CFStringRef variable and don't mind using Foundation then the easiest thing to do is use one of NSString's initializers that read from the file system and cast it out of ARC:

NSString * string = [NSString stringWithContentsOfFile:@"/path/to/file" encoding:NSUTF8StringEncoding error:nil];
CFStringRef cfstring = CFBridgingRetain(string);

Of course if you want a pure-CF solution then I would suggest something like this:

FILE * file;
size_t filesize;
unsigned char * buffer;

// Open the file
file = fopen("/path/to/file", "r");
// Seek to the end to find the length
fseek(file, 0, SEEK_END);
filesize = ftell(file);
// Allocate sufficient memory to hold the file
buffer = calloc(filesize, sizeof(char));
// Seek back to beggining of the file and read into the buffer
fseek(file, 0, SEEK_SET);
fread(buffer, sizeof(char), filesize, file);
// Close the file
fclose(file);
// Initialize your CFString
CFStringRef string = CFStringCreateWithBytes(kCFAllocatorDefault, buffer, filesize, kCFStringEncodingUTF8, YES);
// Release the buffer memory
free(buffer);

In this case you need to use standard C library functions to get a byte buffer of the file contents. If you were dealing with file too large to load into a memory buffer then you could easily use the mmap function to memory-map the file, which is what NSData does in many cases.


Need Your Help

Google API translation return error

java google-api

i have a part of code that use google api translate , i write my code like this

JavaFX : Embedding a browser other than available webview with JavaFX

java css javafx webkit javafx-webengine

I am working on a JavaFX application which contains few html,css,JS files which are rendered by the internal webkit browser. Now, the problem is the CSS animations which we have are not getting ren...