テキスト ファイルを読み取り、それを変数 (CFStringRef) にコピーする最も簡単で簡単な方法は何ですか?
1113 次
1 に答える
4
単純に CFStringRef 変数を使用するだけで、Foundation を使用することを気にしない場合、最も簡単な方法は、ファイル システムから読み取り、ARC からキャストする NSString の初期化子の 1 つを使用することです。
NSString * string = [NSString stringWithContentsOfFile:@"/path/to/file" encoding:NSUTF8StringEncoding error:nil];
CFStringRef cfstring = CFBridgingRetain(string);
もちろん、純粋な CF ソリューションが必要な場合は、次のようなものをお勧めします。
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);
この場合、標準の C ライブラリ関数を使用して、ファイルの内容のバイト バッファーを取得する必要があります。ファイルが大きすぎてメモリ バッファにロードできない場合は、mmap 関数を使用してファイルをメモリ マップすることが簡単にできます。これは多くの場合 NSData が行うことです。
于 2014-03-07T17:05:54.487 に答える