Reading from a file in C

Posted: 31st October 2010 by Tim in C
Tags: , , , , , , , ,

Reading data from a file is fairly common. The stdio.h provides us with a function, getline, which allows us to read lines from a file without worrying about buffer overflows and other memory corruption issues that C is famous for.

The following code opens a file named “myfile.txt” and prints out each line with the line number. Notice that we’re not using fgets here, as some other examples do. fgets will truncate a line if it doesn’t fit into your buffer, which is not always useful. getline will re-allocate memory for you if a line is too big to fit into the buffer.

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char **argv)
{
    // the file we want to read from
    char filename[] = "myfile.txt";

    // open the file for reading
    FILE *file = fopen(filename, "r");

    // make sure the file opened properly
    if(NULL == file)
    {
        fprintf(stderr, "Cannot open file: %s\n", filename);
        return 1;
    }

    // set up the buffer to read the line into. Don't worry too much
    // if some of the lines are longer than 80 characters - the buffer
    // will be made bigger if need be.

    size_t buffer_size = 80;
    char *buffer = malloc(buffer_size * sizeof(char));

    // read each line and print it to the screen
    int line_number = 0;
    while(-1 != getline(&buffer, &buffer_size, file))
    {
        printf("%d: %s", ++line_number, buffer);
    }
    fflush(stdout);

    // make sure we close the file and clean up the buffer when we're
    // finished
    fclose(file);
    free(buffer);

    return 0;
}

  1. sasikala says:

    How can i get the lines in reverse order like line numbers from 100 to 1 if a file has 100 lines.