NSFileHandle 大数据量读写操作

浏览 : 10634 次 Wed, 05 Nov 2014 14:11:37 GMT

NSBundle *mainBundle = [NSBundle mainBundle];
    NSString *txtPath = [mainBundle pathForResource:@"output" ofType:@"rtf"];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL exist = [fileManager fileExistsAtPath:txtPath];
    
    if(!exist)
    {
        [fileManager createFileAtPath:txtPath contents:nil attributes:nil];
    }
        


    NSString *lpStringValue = [inputNumber text];


    int megaValue = [lpStringValue intValue];
    
    if(megaValue > 40)
        megaValue = 40;
    
    int blockSize = 4 * 1024;
    
    int nBlocks = megaValue * 1024 * 1024 / blockSize;
    
    unsigned char *buffer = (unsigned char *)malloc(blockSize); // create buffer
    
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:txtPath];
    
    for (int i=0; i<nBlocks; i++) {
        for(int j=0;j<blockSize;j++)
        {
            buffer[j] = rand() %255;
        }
        NSData *data = [NSData dataWithBytesNoCopy:buffer length:blockSize freeWhenDone:NO]; //  freeWhenDone shoule be NO, else will be memory corrupt
        [fileHandle writeData:data];  // after write data , the file pointer will move forward
    }
    
    [fileHandle closeFile]; //  close file handle 
    
    free(buffer); // free buffer

 

 

2 how to read large data from a file

NSBundle *mainBundle = [NSBundle mainBundle];
    NSString *inputPath = [mainBundle pathForResource:@"input" ofType:@"rtf"];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL exist = [fileManager fileExistsAtPath:inputPath];
    if(!exist)
    {
        return;
    }
    
    int blockSize = 4 * 1024;
    
    NSFileHandle *inputFileHandle = [NSFileHandle fileHandleForReadingAtPath:inputPath];

    NSData *inputData = [inputFileHandle readDataOfLength:blockSize];
    
    unsigned char *source = new unsigned char[blockSize];


    int offset = 0;          // if file size is larger than MAX int value, please use long, or long long type 
    while ([inputData length] > 0 && [outputData length] >0) 
    {
        [inputData getBytes:source length:blockSize];
      
        offset += [inputData length];
        
        [inputFileHandle seekToFileOffset:offset];        
        
        inputData = [inputFileHandle readDataOfLength:blockSize];   // unlike write data , read data of length will move the file pointer, so we need do ourselves
    }
    
    delete [] source;
    
    [inputFileHandle closeFile];