Martin Broadhurst

Reading a Text File in C

This is a little library to solve the perennial problem of reading a text file line by line in C.

Here is an example of its use:

#include <stdio.h>

#include "textfile.h"

int main(void)
    const char *line;
    MBtextfile *file = MBtextfile_open("test.txt");
    if (file) {
        while ((line = MBtextfile_read(file)) != NULL) {
            printf("%s\n", line);
    return 0;

You can open a file with MBtextfile_open and close it with MBtextfile_close, or wrap an already-open file with MBtextfile_create and MBtextfile_delete. You mustn't mix ordinary reading of the file with calls to MBtextfile_read though, as the file is buffered, so the file position after reading a line is not necessarily at the end of the last line read.

Lines can be of any length (up to size_t - 1 characters), and Unix or DOS line endings are handled correctly. A blank line will produce an empty string. The carriage returns at the ends of the lines are discarded. After the last line has been read, MBtextfile_read returns NULL.

Copyright (C) 2010 Martin Broadhurst