Advanced File Handling
We can also read a line from the file. The benefit of reading a line is efficiency. But clarity should not be sacrificed over efficiency. We read from the disk and write to the disk. The disk is an electro mechanical device. It is the slowest component in the computer. Other parts like processors, memory etc are very fast nowadays i.e. in Ghz. When we talk about hard disk, we say its average access time is 7 mili sec. It means when we request hard disk to get data it will take 7 mili sec (7/1000 of a sec) to get the data where as processor is running on GHz speed, a thousand million cycles per sec. Processor and memory are much much faster than the hard disk. Therefore reading a single character from the file is too slow. Nowadays, the buffering and other techniques are used to make the disk access faster. It will be quite efficient if we read the data in bigger chunks i.e. 64k or 256k bytes and also write in bigger chunks. Today’s operating system applies the buffering and similar techniques. Instead of reading and writing character-bycharacter or word-by-word, reading and writing line by line is efficient. A function is available for this purpose i.e. getLine() for input file stream and putLine() for output file stream. The syntax of getLine() is as follows:
The first argument is a character array. The array should be large enough to hold the complete line. The second argument is the maximum number of characters to be read. The third one is the character if we want to stop somewhere. Suppose we have an input file containing the line ‘Hello World’, then the statements:
The getLine() function will read ‘Hello ’. Normally we do not use the third argument. The default value for the third argument is new line character so getLine() will read the complete line up to the new line character. The new line character will not be read. The line read will be stored in the array, used in the first argument. It is our responsibility that the array should be large enough to hold the entire line. We can manipulate this data. Using the getLine() repeatedly to read the file is much more efficient rather than using the get() function. As the getLine() function does not read the new line character, we have to put it explicitly. If we have large file to be read, the difference in speed with both the programs i.e. using get() and getLine() can be noted.
Write a program which reads a file using the getLine() function and display it on the screen.
Sample input file:
The complete code of the program:
char inputFileName = "test.txt";
The output of the program is: