Question

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

No correct solution

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top