How to Read a File in ANSI C

Written by jaime avelar
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Read a File in ANSI C
(Ciaran Griffin/Lifesize/Getty Images)

One of the first things you learn as a C programmer is how to read data from a file. Though it was developed in 1972, the C programming language is still commonly used today, mostly because it allows the programmer to develop high-level applications while still being able to control individual bits of information if needed. Write a program to read a text file in just a few steps.

Skill level:


  1. 1

    Type the following to include the "ansi_c.h" header file in the very first line of your Source file:

    include <ansi_c.h>

  2. 2

    Type the following in a new "ANSI C" project to define the "readFile" function:

    int read File(const char filePathName, char *results Read)


  3. 3

    Type the following to open the file:

    int sizeOfFile = 0;

    FILE *file Pointer = fopen(filePathName, "rb");

    if (file Pointer == NULL)


    *results Read = NULL;

    return -999;


  4. 4

    Type the following to read the contents of the file:

    fseek(file Pointer, 0, SEEK_END);

    sizeOfFile = ftell(filePointer);

    fseek(file Pointer, 0, SEEK_SET);

    results Read = (char )malloc(sizeOfFile+1);

  5. 5

    Type the following to check for errors while reading file:

    if (sizeOfFile != fread(*results Read, sizeof(char), sizeOfFile, file Pointer))



    return -999;


  6. 6

    Enter the following to close the file and return file contents:


    (*resultsRead)[sizeOfFile] = 0;

    return sizeOfFile;


  7. 7

    Type the following to define the "main()" function in your Source file:

    int main ()


    Type the following to declare your variables:

    char *data Read;

    int sizeOfFile;

    int characterCntr = 0;

  8. 8

    Enter the following to call the "readFile" function you created above:

    sizeOfFile = read File("C:\readData.txt", &data Read);

    if (sizeOfFile < 0)


    puts("Error reading data in file");

    return 1;


  9. 9

    Input the following to loop through the contents in your file, display them and close the function:

    while (sizeOfFile > 0)


    putchar(data Read[characterCntr]);




    return 0;


Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.