我fcntl(fd, F_GLOBAL_NOCACHE, 1);
从磁盘读取文件而不是从缓存读取文件。读取文件后,我只能获取字符串数据。现在我想在读取文件后,将文件的字节数据获取到 NSMutableData。我怎样才能做到这一点?提前致谢。
if (fd)
{
fcntl(fd, F_GLOBAL_NOCACHE, 1);
NSMutableData* myData = [[NSMutableData alloc] init];
while(YES)
{
// store the length before addition
NSUInteger previousLength = [myData length];
// increase the length so we can write more bytes
[myData increaseLengthBy:300];
// read bytes from stream directly at the end of our data
size_t len = fread([myData mutableBytes] + previousLength, 300, 1, fd);
// set data length
[myData setLength:previousLength + len];
// if end-of-file exit the loop
if (len == 0) {
break;
}
[myData appendBytes:buffer length:len];
}
// use your 'myData'
NSLog(@"dataFile: %@",myData);
[myData release];
请给我建议?谢谢
UPDATE2: 现在我有另一个问题:我想直接从磁盘而不是从缓存中读取文件。我使用了下面的代码,但它似乎不起作用,它仍然从 Cache 读取:
NSString *url= [NSString stringWithFormat:@"%@/demo.abc"];
const char *c_sd_url = [url UTF8String];
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
FILE * fd = fopen(c_sd_url, "rb");
if (fd)
{
fcntl(fd, F_GLOBAL_NOCACHE, 1);
fseek(fd, 0, SEEK_END);
long sz = ftell(fd);
fseek(fd, 0, SEEK_SET);
char *buf = malloc(sz);
NSLog(@"before %s",buf);
assert(buf != NULL);
assert(fread(buf, sz, 1, fd) == 1);
NSLog(@"after %s",buf);
NSMutableData *data= [NSMutableData dataWithBytesNoCopy:buf length:sz freeWhenDone:YES];
NSLog(@"%@",data);
}
我fcntl(fd, F_GLOBAL_NOCACHE, 1);
在 fopen() 之后使用。请给我任何建议。非常感谢