C Tutorial File Handling Commands

How to Open, Close, Read, Write, Append and Delete Files in C Code

© Guy Lecky-Thompson

May 8, 2007
A discussion of using stdio.h to manipulate files to open, close and delete files, and read/write data to/from them for C programmers.

Introduction

Part of any useful computer program is often going to be manipulation of external data sources. The file is the basic unit of storage for many operating systems, from Unix to Mac. Any C development environment on these platforms will include functions allowing the programmer to:

  • Open & Close files;
  • Read from & Write to files;
  • Delete files.

Commands for all of the above are found in the stdio.h header file.

Opening & Closing Files

The basic command used to open a file is:

FILE * fopen(char * filename, char * mode)

The value returned is a handle to a file, defined in stdio.h, as FILE *. A null pointer is returned and can be tested for in case the call fails. So, the following is a good test for presence of a file:

FILE * hFile;
hFile = fopen( filename, "r");
if (hFile == NULL)
{
// Error, file not found
}
else
{
// Process & close file
fclose(hFile);
}

The mode value in the above example is set to 'r', indicating that we want to read from the file. Other possible values are:

  • w - write to the file, overwriting existing data
  • a - append to an existing file
  • r+ - read and write to a file

Using 'r+' means that all writing will take place at the end of the file, and that reading is sequential. The fclose function closes a valid file handle.

Reading & Writing Data

Once a file is open, we can read from it in one of two ways. We can use the standard printf functions for formatted output, or we can use the 'binary' file functions:

int fread(void * buffer, int size, int num, FILE * hFile)
int fwrite(void * buffer, int size, int num, FILE * hFile)

Both of these can accept any variable that can be cast internally in the first parameter. Be aware, however, that if it is not a pointer type (int *, char * etc.), then it will need to be passed by reference (&nNumber, for example). This will create the appropriate cast to the variable being passed. So, to read a number, we would use:

int nRead = fread(&nNumber, sizeof(int), 1, hFile);

In this example, we have provided the size of an integer (since we don't know the platform that we are compiling for), and a count of 1. This will cause the program to read the appropriate amount of data. We can also write the data back out using:

int nWritten = fwrite(&nNumber, sizeof(int), 1, hFile);

Of course, if we were to have a string that needed to be written to the file, so long as it is null terminated, we can use fwrite as follows:

int nWritten = fwrite(szString, sizeof(char), strlen(szString), hFile);

This will write out the string, but not the null terminator. Care, therefore, must be taken when using this function.

If we want to read the data back in, without knowing the length of the string, we need to perform two operations for each file access:

int nStrLen = strlen(szString);
int nWritten = fwrite(&nStrLen, sizeof(int), 1, hFile);
int nWritten = fwrite(szString, sizeof(char), nStrLen, hFile);

We can then read the variable length string back in as follows:

int nStrLen;
int nRead = fread(&nStrLen, sizeof(int), 1, hFile);
int nRead = fread(szString, sizeof(char), nStrLen, hFile);
szString[nStrLen] = '\0'; // Append null terminator

This trick can be used for any data types, including user defined data types, such as structs.

Deleting Files

The command to delete a file is:

remove (char * szFileName);

This will simply delete the file, with no way to get it back again without an external program.


The copyright of the article C Tutorial File Handling Commands in C Programming is owned by Guy Lecky-Thompson. Permission to republish C Tutorial File Handling Commands in print or online must be granted by the author in writing.




Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo

Comments
May 25, 2007 8:06 AM
navinkrsna :
I'm trying to write and read a user defined datatype(created
through struct) using fwrite and fread, taking help of a void pointer
as follows:

Record record,record1;
int i;
void *buff;

f1=fopen("./conf.txt","a");

if(f1!=NULL)
{
do{
printf("\nenter source_IP and dest_IP \n");
scanf("%s%s",&(record.source_IP),&(record.dest_IP));
printf("\nenter source_port and dest_port\n");
scanf("%s%s",&(record.s_port),&(record.d_port));
printf("\nenter start and end time of restricted period\n");
scanf("%s%s",&(record.range_disallow[0]),&(record.range _disallow[1]));

buff=&record;
fwrite(buff,sizeof(Record),1,f1);
fflush(f1);
printf("\n more records? say 1 or 0 for yes /no:");
scanf("%d",&i);
}while(i==1);
fclose(f1);
}
f2=fopen("conf.txt","r");
if(f2!=NULL)
{
//reading not taking place!!!!!!
while(fread(buff,sizeof(Record),1,f2)>0)
{
record1=*((Record*)buff);
printf("%s %s %s %s",record1.source_IP,record1.dest_IP,record1.s_port,record1.d_port);
}
fclose(f2);
}

though fwrite works properly, trying to see if record1 has been filled correctly gives (Segmentation Fault)error during printf.

Could you please help?
May 15, 2008 2:54 AM
Guest :
at last i understand file handling
2 Comments