You read a file in Ada by declaring a File_Type variable, calling Open or Create on it with a Form string that names the file, and then passing that file as the first argument to Get_Line, Get, or Ada.Text_IO.End_Of_File. The key condition is that the file mode must match what you intend to do: In_File for reading, and the file handle must be closed when you're done so buffers flush and the operating system releases it.

That answer covers a text file of modest size. The details below handle the parts that usually trip people up: the form string's quotes, end-of-line differences between Unix and Windows, reading numbers versus strings, what happens at end of file, and when Ada.Text_IO is the wrong tool entirely.

What You Need Before the First File Operation

Two things must be true before any file code runs. First, your program needs with Ada.Text_IO; and usually use Ada.Text_IO; at the top, so File_Type, Open, Get_Line, and the rest resolve. Second, the process must have operating-system permission to read the file you name, because Ada's file operations map onto the OS's own calls. A program that compiles cleanly will still raise Name_Error if the path is wrong and Use_Error if permissions or mode settings don't line up.

Decide the path convention up front. In the form string, plain "data.txt" means the file in the process's current working directory, which is not necessarily the directory containing your executable. Absolute paths work but tie the program to one machine. A middle path is to accept the filename as a command-line argument, which Ada.Command_Line.Argument (1) gives you; then the same binary runs anywhere.

Also settle the access mode. In_File is read-only but requires the file to already exist. Inout_File reads and writes but also requires an existing file. Out_File truncates or creates. If you want to read a file that might not exist yet, check with Ada.Text_IO.Is_Readable or handle the exception, which the error section below covers.

Opening a File the Reliable Way

Wrap the open in a block so a failure can't leave a handle dangling:

Three things in that snippet matter. Open takes the file variable as its first parameter, the mode second, and the external name last. The external name is a String, so if you build it from a variable, concatenate with & and pass the result; the identifier in your source has no relationship to the filename on disk. And Close sits on the normal path, not only in the exception handler, because an unclosed file may not have its data flushed.

The order of operations is fixed: declare, open, read, close. Reading before opening raises Status_Error, and opening an already-open file also raises Status_Error. If you write a reusable procedure, guard it with if Is_Open (F) then Close (F); end if; before opening, so a retry doesn't fail on a stale handle.

To confirm success without exceptions, Is_Open (F) returns True after a successful Open. That's your check for the reversible case; if the open raised, control never reaches the read loop.

Reading Line by Line With Get_Line

For most text formats, lines are the right unit. Get_Line reads up to and including the line terminator and returns the content without it:

Last reports how many characters were actually stored. Ignore it and you print the uninitialized tail of the buffer, which is the single most common bug in Ada file code. The buffer must be big enough for the longest line; a line longer than the buffer raises Layout_Error rather than truncating quietly.

There's an overload of Get_Line that returns a String directly: declare S : constant String := Get_Line (F); begin ... end;. It's convenient but allocates a new string per line and will hit Storage_Error on very long lines or very large files. For scripts and small configuration files, that trade is fine; for a log of a million lines, use the buffer form.

An important detail: End_Of_File (F) becomes true only when the reader has consumed every character, including a final line without a trailing newline. A file whose last line has no terminator is read correctly, and the loop exits right after processing it. You don't need a separate peek at the last character.

Reading Words and Numbers With Get

When the data is space-separated rather than line-separated, Get skips leading whitespace and reads one item. Typed Get procedures do the conversion for you:

Get for numbers raises Data_Error when the text isn't a valid literal for the type. That's usually preferable to silently reading garbage, but it means a malformed input file crashes the program unless you handle it. Validation strategy matters here: wrapping each Get in a handler catches a bad token, but recovering the stream position after a Data_Error is awkward because the failing characters have been partly consumed. The practical fix is to read lines first, then parse each line in isolation, so one bad record doesn't corrupt the rest.

Watch the integer type. Integer is guaranteed to hold at least 16 bits, which is only -32,768 to 32,767. Files containing larger values need Interfaces.Integer_32, Interfaces.Integer_64, or a Long_Integer, and Ada.Text_IO.Integer_IO must be instantiated for whichever type you choose. The default Get for Integer will raise Data_Error on an out-of-range literal rather than wrap.

Handling End-of-Line, End-of-File, and Blank Lines

Ada distinguishes end of line from end of file, and that distinction bites people in two places. First, Get never chews through a line terminator while reading numbers, so a mixed loop that reads a number then calls Get_Line will see an empty line. The standard remedy is Skip_Line after the final Get in a line's worth of data. Second, an empty line is a legitimate Get_Line result of length zero; you can only tell it apart from end of file with the End_Of_File check.

A frequent failure looks like this: a file has Windows line endings (CR LF) and is processed on a Unix-like system. Get_Line strips the LF but may leave the CR as the final character of the line, so string comparisons against expected values fail. Ada.Text_IO doesn't normalize line endings, so trim trailing CR characters yourself when the source platform is unknown.

For column-oriented data, Ada 2005 added Get_Line overloads and Ada.Text_IO gained no column splitting; you slice with Line (Start .. Stop) after finding separators. Comments in a data file, such as lines beginning with #, are trivial to skip: test the first character after Get_Line and loop again. This pattern is worth memorizing because nearly every real input file has comments or a header line.

Whole-File and Streaming Approaches

Ada.Text_IO is line-oriented and unsuitable for binary data. Two alternatives exist within the standard library. For raw bytes, Ada.Streams.Stream_IO gives you Read and Write on arrays of Stream_Element, with modes, forms, and the same exception structure; use it for images, serialized records, or any file the text layer would corrupt.

For an entire text file in memory, read it with the buffer Get_Line loop into an Ada.Containers.Vectors of String, or natural-sized buffers, and close the file before parsing. Years of performance advice say to avoid interleaving I/O and computation; the file comes off disk in one pass, then the parse gets the whole picture. I recommend this for configuration files and anything under a few megabytes. Above that, stream, parse, and discard line by line so the memory ceiling stays flat.

For very large files where line-by-line allocation is still too expensive, the streaming text layer is already close to the right shape: one buffer, reused each iteration, Get_Line overwriting it. Don't allocate per line in that mode.

Reading Paths, Platform Differences, and Encodings

The form parameter's definition is implementation-defined, and GNAT's convention is a string of the form "filename" or parameter pairs like "name=value". Plain filenames work everywhere; portability of anything beyond that is not guaranteed. Ada.Directories gives the portable way to combine paths, Compose, and Containing_Directory for navigation, but those calls feed into the external name, they don't change Open's signature.

Today's compiler defaults read source in UTF-8 and Character is Latin-1-shaped, so a String read by Get_Line isn't a Unicode text. A UTF-8 file containing accented characters yields a sequence of Character values that print wrongly unless the consumer knows the encoding; there's no transcoding in Ada.Text_IO. For text with non-ASCII content, read bytes with Stream_IO and decode explicitly, or restrict yourself to ASCII fields and validate. I've seen this trip up address files and names.

One more caution: on some systems, text-mode translation converts line endings automatically, on others it doesn't, and Ada's portable layer can't close the gap. Keep data files in a defined convention and normalize where you read them.

Errors, Exceptions, and the Reversible Checks

The exceptions you should expect: Name_Error for a nonexistent or inaccessible name, Use_Error when the mode is wrong for the file's state, Mode_Error when you try to read in a writing mode, End_Error on reading past the end, Data_Error on malformed typed input, Status_Error on an operation against an unopened or already-open file, and Layout_Error on lines too long for the buffer. End_Error rarely surfaces in practice because the End_Of_File loop exits first, but it's the one a Get-based loop can hit.

The first checks to try, in order, are the reversible ones: print the resolved working directory near the top of the program, confirm the external name string, and check Is_Open before opening. If those are clean, the exception handler's specific name usually points straight at the cause. A subtle case is the file being open in another program: Use_Error covers it on platforms that honor exclusive access, and retry loops with a short delay are a legitimate workaround, though structuring the program so files aren't shared is cleaner.

Stop condition: if the name is right, permissions are sound, and the exception persists, the problem is now the OS, the path resolution in a launch context you don't control, or a bad form string, and that's where a local systems administrator's help is warranted rather than more code changes. Reading a file is a bounded, well-understood operation.

A Complete, Runnable Program

Here's a self-contained reader that takes a filename, prints numbered lines, and reports a missing file cleanly:

Compile with gnatmake read_file.adb on any GNAT installation, including the free GNAT Community toolchain, and run it as ./read_file data.txt. The success check is simple: numbered output for every line, no exception, and the program exits normally. Test the failure path too, with a nonexistent name, and confirm you get the single error line instead of a crash trace.

The one-liner at the top of this article is the whole answer; everything after it is the part you can't avoid running into. Declare, open with the right mode, read with Get_Line, respect Last and End_Of_File, close, handle the named exceptions, and you'll cover the vast majority of real text-file input in Ada.