{ inputFiles.p Started by Jeff Ondich on 2/29/96 Last modified 2/29/96 This program illustrates the use of text files in a gpc Pascal program, by asking the user for a file name, opening that file for reading, counting the lines and characters in the file, closing the file, and, finally, reporting the results of the counting. Some things to note: 1. The type "text" is a built-in type. It's actually a record, containing lots of information the computer needs to find the file on the hard disk or elsewhere. 2. All variables of type text must be global, and included in the "program" line's parameter list. You may pass variables of type text, but you should always pass them as variable parameters. If you pass text files as value parameters, you can get some weird behavior. 3. eof, eoln, read, and readln all take an extra parameter that they don't take when they are reading from the keyboard (or a file piped in using the Unix "<" facility). Thus, read( c ) will read from the keyboard, whereas read( theFile, c ) will read from theFile. } program inputfiles(input,output,inFile); var inFile : text; inFileName : string(40); nLines, nChars : integer; c : char; { FileCounter Precondition: theFile has been opened for reading using reset() Postcondition: chars and lines contain the number of characters and lines, respectively, in theFile. theFile has not been closed, but its entire contents have been read. } procedure FileCounter( var theFile : text; var chars, lines : integer ); var c : char; begin lines := 0; chars := 0; while not eof(theFile) do begin while not eoln(theFile) do begin read( theFile, c ); chars := chars + 1 end; readln( theFile ); chars := chars + 1; lines := lines + 1 end end; begin {Ask the user for a file name} write( 'What file do you want to count? ' ); readln( inFileName ); {Open the file, count its lines and characters, and close the file} reset( inFile, inFileName ); FileCounter( inFile, nChars, nLines ); close( inFile ); {Report the number of lines and characters in the file} write( inFileName, ' has ' ); write( nLines:3, ' lines and ' ); writeln( nChars:3, ' characters.' ) end.