2011-12-16 41 views
1

FileHandle類中有一個fileHandleWithStandardOutput方法。根據Documentation,「傳統上這是一個接收來自程序的數據流的終端設備。」Objective C 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的fileHandleWithStandardOutput返回NSFileHandle ..

我嘗試了before..but它沒有worked..and現在它的工作。可能還有別的東西或者是干擾的東西。無論如何,我現在得到了答案。

回答

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]; 
+0

WOW!你的代碼比我的WAAAAYYYY好。非常好!謝謝! – jovhenni19 2011-12-16 05:30:23

0

您可以簡單地這樣做達到你的目的:

while ((buffer = [inFile readDataOfLength:kBuffSize]).length !=0){ 
    [standardOutPut writeData:buffer]; 
}