In the previous section, you learned how to display all the lines available in a text file. Now, let us see how to count the number of lines in a text file. I modified the program in the previous section to meet the new requirement. The program is as follows:
declare f utl_file.file_type; s varchar2(200); c number := 0; begin f := utl_file.fopen('SAMPLEDATA','sample1.txt','R'); loop utl_file.get_line(f,s); dbms_output.put_line(s); c := c + 1; end loop; exception when NO_DATA_FOUND then utl_file.fclose(f); dbms_output.put_line('Number of lines: ' || c); end;
According to the above program, I am defining a simple variable to maintain the count. That variable always gets incremented within the loop, thus maintaining the number of lines read!
You can also observe that I am handling the last part of my program only in the “exception” area. The exception part gets executed only when no lines are available to read. In my upcoming articles, I shall explain how to deal with these types of scenarios very professionally. Till then, I shall continue in this fashion.