Ada doesn't give you a single "is the file over?" switch. You determine the end of a text file by combining the current file position with each file's declared end-of-file marker, which defaults to the newline character and can be set to a different character or to no character at all. The key condition is this: a text file is finished only when the position points at the end line and that line is immediately followed by the end-of-file marker current for that file. Read one line ahead of the check, handle the final character of the marker separately, and most off-by-one bugs disappear.

That's the short version. The rest of this article unpacks why the rule works, how to implement it in sequential and direct-file code, what to do with empty lines, missing final newlines, and files whose structure doesn't fit a marker at all.

Why Ada Uses a Position-and-Marker Model Instead of a Simple Boolean

Ada's input/output model comes from the language's original design as a systems and safety-critical language, and text files reflect that lineage. A text file in Ada is inherently a sequence of lines, with each line made of characters. The line terminator is not a character you see in your data; it's the end-of-file marker plus the end-of-line concept, and the marker itself is configurable.

Two functions in Ada.Text_IO describe where you are:

End_Of_File (File) returns true when a subsequent read would fail because nothing remains. End_Of_Line (File) returns true when a subsequent character read on the current line would exhaust that line.

But the way these interact with the marker is what trips people up. If you call Set_End_Of_Line (File, Marker), the file's marker becomes Marker, and Ada treats that character as a line separator at the output side. On input, the marker character is consumed as a line break, not returned as data. This means that if your marker is something other than the newline (for a plain text file), an occurrence of the marker character in the data will silently terminate the line view — but it won't terminate the file unless it coincides with the true end of file.

So "end of file" is a compound observation, not a flag you set. You ask the file system (through the runtime) whether the next read would succeed. Ada answers by checking both position and marker.

The practical consequence: you cannot trust a single "has the file ended?" call if you've been mixing Get_Line and raw Get operations, because each has different effects on position. A reliable routine should use one consistent reading style and account for the marker's status relative to the last data.

Prerequisites Before You Write a Single Check

Before any detection routine makes sense, confirm four things about your environment and file.

Set the file mode and form explicitly. Ada.Text_IO.Open on an existing file, or In_File via Create/Reset, must specify a form string you control. Common forms like "shared=no" or a purely default form are fine, but the marker default is newline unless you've changed it. If the file was produced by a tool that uses a different marker (notably some systems use a substitute character), you must tell Ada.

Choose a reading style. Either line-oriented (Get_Line, Skip_Line, End_Of_Line) or character-oriented (Get (Item : out Character), End_Of_File). Mixing the two is legal but makes reasoning about position fragile. Pick one style per routine.

Decide how empty lines count. In a line-oriented model, a file ending with two newlines has one empty line followed by the end marker; a file ending with one newline has a completed final line and nothing after it. The line and marker rules produce different answers, and both are legitimate depending on what you're parsing. Write down which one your consumer expects.

Know whether the last line has a terminator. Text files produced by many Unix tools end with a newline. Files assembled by naive scripts often don't. If the producer omitted the final marker character, Ada will still let you read the final line's characters, but the end-of-file check must not assume the marker is present. This is the single most common source of "last record disappeared" bugs.

If you can't confirm these four points, don't guess. Open the file read-only and inspect the final byte or two with a hex viewer to see whether a terminator character exists at all.

Step-by-Step: Detecting the End of a Text File

The ordered procedure below assumes line-oriented reading with the default newline marker. Each step names the result to expect and a way to verify it.

  1. Open the file in In_File mode.

Expected result: a valid file handle. Check: if Open raises Ada.Text_IO.Name_Error, the path or form is wrong; stop and fix that before anything else. Never proceed with an unopened file.

  1. Confirm the file is non-empty, but don't rely on it to mean "data exists."

The first End_Of_File (F) call after a successful open returns False for a non-empty file and True for a zero-byte file. That sounds definitive. It isn't quite: if the file contains only the marker character (a single newline), End_Of_File returns False, but reading a line yields an empty line. So an empty line and an empty file are distinct states that both pass the initial check. Note which one you're in by reading the first line.

Expected result: you now know whether the file has any bytes. Check: a file containing exactly one ambient newline passes this test but yields a single empty line when read in step 3.

  1. Read lines in a loop that checks End_Of_File after each read, not before.

Expected result: every complete line is processed exactly once. Check: a file with three lines and a terminating newline produces three calls to Process. A file with three lines and no terminating newline also produces three calls. If you see only two, the file likely contains an embedded marker character treated as a line break by Set_End_Of_Line; inspect the raw bytes.

This ordering — exit before the read, and reading only after the check confirms data remains — is the safe default. The alternative ordering, read-then-check, works for well-formed files but can attempt a read past the end, which Get_Line will reject.

  1. Distinguish end-of-line from end-of-file when you need the final character.

Get_Line strips the terminator, so if you need to know whether the last line was terminated, do a raw read on the line's contents using Get. A line whose characters are followed directly by End_Of_File returning true was terminated; a line whose characters run to End_Of_File without a marker was not. Internally, the routine you want is: while not End_Of_Line and not End_Of_File, read characters; then check which condition fired.

Expected result: you can tell a terminated final line from an unterminated one. Check: a file "abc\n" ends with End_Of_Line first; a file "abc" ends with End_Of_File first. This distinction is exactly what you need for parsers that treat a missing final newline as an error.

  1. Close the file and confirm no exception escaped.

Expected result: clean shutdown. Check: any Status_Error during the loop (attempting to read a closed file) or Use_Error during open means the file object wasn't in the expected state; reopen and inspect.

The stop condition for troubleshooting is simple: if repeated verified reads still disagree with the raw byte count from an external tool, stop adapting your code and inspect how the file was produced. Marker-mismatch problems are a producer-side property, not something you can fix with more defensive reads.

The Empty-Line and Missing-Final-Newline Edge Cases

Two cases account for most "the end of file isn't where I expected" reports.

An empty line is data, not an end signal. In line-oriented Ada, Get_Line on a blank line returns an empty string, and End_Of_File remains False if a marker follows. A file containing "a\n\nb\n" has three lines: "a", "", "b". If your processing logic skips empty strings as noise, you'll silently drop that middle line and may conclude the file ended early. Make the skip explicit, and log it in test runs.

A missing final newline is a marker problem, not a data problem. Consider "a\nb". Get_Line returns "a", then "b", then End_Of_File is true. You got both lines. Now consider "a\nb\n": identical results. The difference only shows if you use End_Of_Line/Get rather than Get_Line, or if a later direct-file read assumes a fixed record structure. The general rule: Get_Line-based loops are robust to a missing final marker; raw-character loops are not, and you must check End_Of_Line before End_Of_File in the correct order, as in step 4.

Files that are all marker characters. A file of "\n\n\n" yields three empty lines. If your parser requires a non-empty final record, detect this by tracking whether the last read returned a non-empty string and combining that with the step 4 check.

Working with End_Error Instead of Polling

A different style avoids End_Of_File entirely and drives termination by exception.

This is idiomatic Ada and is recommended in many style guides because the language's predefined exceptions are designed for exactly this flow. Get_Line raises End_Error when there is no line to return, including after the final line if the file ends with a marker, and you exit cleanly. A close variant is while not End_Of_File (F) loop ... end loop, which is equally correct but reads as a poll. Use the exception form if your team's style favors it; use the poll form if you want the loop condition visible at a glance. Both are robust to a missing final newline because Get_Line only raises after the last real line is delivered.

Do not combine the two in the same loop. The exception form without an end of file guard is already complete; adding a guard that calls End_Of_File mid-loop is redundant and can interact badly with buffered Get state.

What About Direct Files, Binary Content, and Non-Text Streams?

Text-file end detection applies only to files opened with Ada.Text_IO. If you need to read a file that mixes text and binary data, or whose "end" is defined by a length field or a sentinel record rather than a line marker, switch to Ada.Direct_IO or Ada.Sequential_IO and treat the file as an array of fixed-size elements. In Direct_IO, the equivalent questions are whether the current index exceeds the file's element count — obtainable with Size (File) — or whether a read raises End_Error past the last element. There's no marker involved, so none of the marker pitfalls apply, but the final element may be shorter than the element type; Ada reports a Data_Error or End_Error on a partial read, which is your signal to handle a trailing fragment explicitly.

For streams, Ada.Streams.Stream_IO reads bytes and you control record framing yourself. End of file is simply "no more bytes accepted by Read," and you should check the count returned rather than rely on exceptions, since a partial read of the final record is valid.

A useful distinction: text-file end detection is semantic (does a valid line remain?), direct-file end detection is positional (is the record index in range?), and stream end detection is count-based (did the read fill the buffer?). Choose your check to match the abstraction, not the other way around.

Character Encoding and Platform Terminator Differences

Ada's Character type is a byte-oriented character set in the standard, and text-file markers are single characters. On systems where lines end with carriage-return plus line-feed (CR LF), the default marker is still the newline, so Ada treats CR as ordinary data. If your file uses CR LF and your code calls Get_Line, each returned line may end with a stray carriage-return character. That stray CR is not the file's end; it's part of the line's last character position. If you treat Character'Val (13) as a signal to stop, you'll truncate lines, not files.

For Unicode text, Ada.Text_IO with Character gives you UTF-8 bytes as individual characters; multibyte sequences are not merged. End-of-file logic is unaffected — the marker remains a byte value — but any routine that counts characters will disagree with a code-point count. If that matters, decode explicitly before applying end checks, and never infer file end from a byte value that happens to appear in a multibyte sequence.

The real cross-platform hazard is producer-side marker substitution. A tool that writes a marker other than newline and a tool that reads it with the default will disagree about where lines end, so End_Of_File can return true later (or earlier) than expected. If you interoperate with such a tool, set the marker explicitly on both ends with Set_End_Of_Line, and document the form string in the code. Since this depends on the specific tool version and platform, verify the producer's output with a hex viewer before trusting the setting.

A Worked Estimate: Counting Lines and Predicting the Final Check

Text file "alpha\nbeta\ngamma\n" has 18 bytes, with three newline markers. Using the loop from the procedure section, you call End_Of_File four times (before each of the three reads, plus once after the last line when the loop condition re-evaluates). The count of reads equals the number of markers (three), and End_Of_File flips to True only after the final marker has been consumed. Drop the final marker to get "alpha\nbeta\ngamma" (17 bytes): you still make three reads, but the last read ends with End_Of_File true rather than End_Of_Line true, so a routine that asserts "every line was terminated" would fail. Add one marker instead ("alpha\nbeta\ngamma\n\n", 19 bytes): three reads of non-empty lines plus one read of the empty line, four reads total. These arithmetic patterns are reproducible and are the fastest way to write a unit test's expected-value table.

The mistake to avoid is assuming End_Of_File becomes true exactly once, at the number of lines plus one. It becomes true at the first position from which no further line can be read, which may be after an empty line, after an unterminated final line, or after a completely empty file. Test all three.

When This Approach Stops Being the Right Tool

If your file is not line-structured at all — a JSON array written without newlines, a CSV whose last record lacks a terminator and whose parser treats the final field specially, or a log where the end is defined by a sentinel timestamp — don't force text-file end detection onto it. Use Direct_IO with a known record layout, or read to a stream end and parse the accumulated buffer yourself. The symptom that you've overfit is this: your code passes tests on typical files and fails on exactly the files your producer's documentation calls "final record without terminator." That's a specification mismatch, not a bug in Ada.

You can also overfit the exception style: an End_Error handler placed too broadly will swallow parsing errors in the middle of a record that happen to surface as End_Error. Scope the handler to the read call itself, as in the example, not the whole record-processing block.

Once these conditions and edge cases are explicit, Ada's end-of-text-file model is consistent and testable. The routine you write should state, in order, which file mode was used, which reading style, how empty lines are treated, and whether a final unterminated line is accepted. Any reader of the code can then predict the program's behavior on the four boundary files: empty, marker-only, terminated final line, and unterminated final line.