Finding, opening and closing a text file for reading C program example


Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows Xp Pro with SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info:

To do: Finding, opening and closing a text file for reading using C file input/output functions

To show: How to use the C file input/output functions in opening text file for reading


At the beginning there is no tkk1103.txt text file in C:


// Opening and closing file example

#include <stdio.h>


// SUCCESS = 0, FAIL = 1 using enum



int main (void)


FILE *fptr;

errno_t err = 0;


// the filename is tkk1103.txt and located in the C:\ folder. For other location, provide the full path

// e.g. "D:\\Myfolder\\test.txt etc

char filename[] = "C:\\tkk1103.txt";

// set the value reval to 0

int reval = SUCCESS;


// test opening file for reading

// if((fptr = fopen(filename, "r")) == NULL), using a secure version

err = fopen_s(&fptr, filename, "r");

// if fail...

if( err != 0)


printf("Cannot open %s.\n", filename);

reval = FAIL; //reset reval to 1


// if successful do...



printf("Opening the %s file successfully\n", filename);

// the program will display the address where the file pointer points to..

printf("The value of fptr pointer is: 0x%p\n", fptr);

printf("\n....file processing should be done here....\n");

printf("\nReady to close the %s file.\n", filename);

// close the file stream...

if(fclose(fptr) == 0)

printf("Closing the %s file successfully\n", filename);


return reval;



Output example:


Cannot open C:\tkk1103.txt.

Press any key to continue . . .


Then create a text file named tkk1103.txt ant put it under the C: and re-run the previous program. The output should be as shown below.


Opening the C:\tkk1103.txt file successfully

The value of fptr pointer is: 0x10310C30

....file processing should be done here....

Ready to close the C:\tkk1103.txt file.

Closing the C:\tkk1103.txt file successfully

Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index