1

FileHandle类中有一个fileHandleWithStandardOutput方法。根据文档,“通常这是从程序接收数据流的终端设备。”

我想要做的是每 128 个字节读取一个文件并将其显示到终端,使用fileHandleWithStandardOutput方法。

这是我如何每 128 个字节读取它的代码片段。

i = 0;
while((i + kBufSize) <= sourceFileSize){
        [inFile seekToFileOffset: i];
        buffer = [inFile readDataOfLength: kBufSize];
        [outFile seekToEndOfFile];
        [outFile writeData: buffer];
        i += kBufSize + 1;        
    }

//Get the remaining bytes...
[inFile seekToFileOffset: i ];

buffer = [inFile readDataOfLength: ([[attr objectForKey: NSFileSize]intValue] - i)];
[outFile seekToEndOfFile];
[outFile writeData: buffer];

kBufSize 是一个预处理器,等于 128;


我的答案:

设置 outFile 返回 NSFileHandle 的fileHandleWithStandardOutput..

我之前试过..但它没有工作..现在它工作了。可能有其他东西或有什么干扰。无论如何,我现在得到了答案。

4

2 回答 2

2

您无需在每次读取或写入 FileHandle 时都进行查找。您的代码可以简化如下:

NSData *buffer;

NSFileHandle *outFile = [NSFileHandle fileHandleWithStandardOutput];

do {
    buffer = [inFile readDataOfLength: kBufSize];
    [outFile writeData:buffer];
} while ([buffer length] > 0);

我不确定您为什么要读取 128 字节的块,但如果没有必要,那么您可以消除循环并执行类似的操作(假设您的输入文件不是那么大,它超过了 NSData 的最大值目的):

NSFileHandle *outFile = [NSFileHandle fileHandleWithStandardOutput];
buffer = [inFile readDataToEndOfFile];
[outFile writeData:buffer];
于 2011-12-16T03:32:17.670 回答
0

您可以通过以下方式简单地实现您的目的:

while ( ( buffer = [inFile readDataOfLength:kBuffSize] ).length !=0 ){
    [standardOutPut writeData:buffer];
}
于 2014-05-28T08:14:37.720 回答