Selecting an I/O Method

Selecting an I/O Method When selecting an I/O method, we take care of simplicity, efficiency and portability. From efficiency point of view, the macros getc ( ) and putc ( ) are usually fastest. However, most operating systems have very fast block I/O operations that can be even faster than getc ( ) and putc ( ). Though efficiency is important but sometimes the choice of an I/O method is based on simplicity. For example, fgets ( ) and fputs ( ) are relatively slow functions, but they are simple in use. Thus, when execution speed is not important, the version using these functions is the best. The last consideration in choosing an I/O method is portability. In terms of deciding between character, line, or block I/O, portability does not play a role. Portability is a major concern in choosing between text mode and binary mode. If the file contains textual data, such as source code files and documents, we should open it in text mode and access it line by line. On the other hand, if the data is numeric and does not have a clear line structure, it is best to open it in binary mode and access it either character by character or block by block.
Unbuffered I/O : We can turn off buffering. To do so, we can use either the setbuf ( ) function or the setvbuf ( ) function. The setbuf ( ) function takes two arguments, the first is a file pointer and the second is a pointer to a character array which is to serve as the new buffer. If the array pointer is a null pointer, buffering is turned off, as by the statement setbuf (stdin, NULL); where the stdin stream is line buffered, requiring the user to enter a newline character before the input is sent to the program. The setbuf ( ) function does not return a value. The setvbuf ( ) function is similar to setbuf ( ), but it is a bit more complicated. It takes two additional arguments that enable us to specify the type of buffering (line, block, or no buffering) and the size of the array to be used as the buffer. The buffer type should be one of the following three symbols (defined in stdio.h)
 _IOFBF block buffering
_ IOLBF line buffering
_ IONBF no buffering
 To turn off buffering, we should write
stat = setvbuf (stdin, NULL, _IONBF, O);

The setvbuf ( ) function returns a non zero value if it is successful. If due to some reason, it cannot honour the request, it returns zero.

No comments:

Post a Comment