Question

In the FileHandle Class there is a fileHandleWithStandardOutput method. According to the Documentation, "Conventionally this is a terminal device that receives a stream of data from a program."

What I want to do is read a file per 128 bytes and display it to the terminal, using fileHandleWithStandardOutput method.

Here's a code fragment of how am I reading it per 128 bytes.

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 is a preprocessor which is equal to 128;


My Answer:

Set outFile the return NSFileHandle of fileHandleWithStandardOutput..

I tried it before..but it didn't worked..and now it worked. May be there is something else or something is interfering. Anyways I got the answer now.

Was it helpful?

Solution

You don't need to seek each time you read from or write to the FileHandle. Your code could be simplified as follows:

NSData *buffer;

NSFileHandle *outFile = [NSFileHandle fileHandleWithStandardOutput];

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

I'm not sure why you're reading in 128 byte chunks, but if that isn't necessary then you could eliminate the loop and do something like this instead (assuming your input file is not so huge it exceeds the maximum for an NSData object):

NSFileHandle *outFile = [NSFileHandle fileHandleWithStandardOutput];
buffer = [inFile readDataToEndOfFile];
[outFile writeData:buffer];

OTHER TIPS

You can simply achieve your purpose by doing:

while ( ( buffer = [inFile readDataOfLength:kBuffSize] ).length !=0 ){
    [standardOutPut writeData:buffer];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top