1

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.

Community
  • 1
  • 1
jovhenni19
  • 450
  • 2
  • 8
  • 24

2 Answers2

2

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];
sjs
  • 8,830
  • 3
  • 19
  • 19
  • 1
    I will tell you why johvenni19 needed to read 128 byte chunks: learning Objective-C using Stephen Kochan's book. I am doing the same now, your code works. It is too bad Apple does not provide code samples like Microsoft does for their SDK. – Eugene Feb 28 '12 at 04:07
  • @Eugene I agree. Apple's documentation is "fine"… but without samples… it creates a perpetual tradeoff between looking _elsewhere_ (somewhere that may also have a sample, i.e. @StackOverflow) AND/OR just using Apple's "official" docs (which you KNOW **won't** include a sample). sigh. – Alex Gray Apr 02 '12 at 05:30
0

You can simply achieve your purpose by doing:

while ( ( buffer = [inFile readDataOfLength:kBuffSize] ).length !=0 ){
    [standardOutPut writeData:buffer];
}
H Lai
  • 2,679
  • 1
  • 12
  • 6