codescracker


c

C File I/O



« Previous Tutorial Next Tutorial »


This tutorial will teach you all about C file system (file handling in C) from very basic to advance. Let's starts with streams and files.

Streams and Files

Before going to discuss about C file system, it is necessary to know about the term streams and files or the difference between streams and files. C I/O system supplies a consistent interface to the programmer independent of the actual device being accessed i.e., the C I/O system provides a level of abstraction between the programmer and the device and this abstraction is called as stream, and the actual device is called as file. Let's discuss about streams.

Streams

The C file system is designed to work with a large variety of devices, including terminals, disk drives, and tape drives. However each devices is very different, the buffered file system transforms each into a logical device called a stream. There are the following two types of streams:

Files

In C language, a file may be anything from a disk file to a terminal or printer. You can associate a stream with a specific file by performing an open operation. And once a file is opened, information can be exchanged between it and your program.

C File System Basics

The C file system is composed of several interrelated functions. Here the following table lists the most common of these functions. These functions require the header file <stdio.h>

Function Name Use
fopen() Opens a file
fclose() Closes a file
putc() Writes a character to a file
fputc() Same as putc()
getc() Reads a character from a file
fgetc() Same as getc()
fgets() Reads a string from a file
fputs() Writes a string to a file
fseek() Seeks to a specified byte in a file
ftell() Returns the current file position
fprintf() Is to a file what printf() is to the console
fscanf() Is to a file what scanf() is to the console
feof() Returns true if end-of-file is reached
ferror() Returns true if an error has occurred
rewind() Resets the file position indicator to the beginning of the file
remove() Erases a file
fflush() Flushes a file

The File Pointer

The file pointer is simply the common thread that unites the C I/O system. A file pointer is a pointer to a structure of type FILE. it points to the information that defines various things about the file, including its name, status, and the current position of the file. Here is the statement to use the file pointers in your C program:

FILE *fp;

Opening a File in C

To open a file in C, use fopen() function. The fopen() function opens a stream for use and links a file with that stream. And then it returns the file pointer associated with that file. Here is the prototype of the function fopen()

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

Here, the filename is the name of the file and mode is the file access mode. Here is the list of all access mode that you can use in opening your file:

Mode Use
r Open an existing text file for reading
w Create a text file for writing
a Append to a text file
rb Open a binary file for reading
wb Create a binary file for writing
ab Append to a binary file
r+ Open a text file for reading/writing
w+ Create a text file for reading/writing
a+ Append or create a text file for reading/writing
r+b Open a binary file for reading/writing
w+b Create a binary file for reading/writing
a+b Append or create a binary file for reading/writing

Here the following code fragment uses fopen() function to open a file named myfile.txt for reading

FILE *fp;
fp = fopen("myfile.txt", "r");

Closing a File in C

To close a file in C, use fclose() function. This function closes a stream that was opened by a call to fopen(). Here is the prototype of the fclose() function

int fclose(FILE *fp);

Here, fp is the file pointer returned by the call to the function fopen().

Writing a Character to a File in C

The C I/O system defines the following two functions that is used in outputting a character to a file. Both functions are equivalent.

Here is the prototype of the function putc()

int putc(int ch, FILE *fp);

Here fp is the file pointer returned by the function fopen(), and ch is the character to be output. If a putc() operation is successful, it returns the character written. Otherwise, it returns EOF (end-of-file).

Reading a Character from a File in C

The C I/O system defines the following two functions that is used in inputting a character from a file. Both the functions are equivalent.

Here is the prototype of the function getc()

int getc(FILE *fp);

Here fp is the file pointer of type FILE returned by fopen() function. The function getc() returns an EOF when the end of the file has been reached.

C File I/O Examples

Now let's take some examples of C File I/O.

C Reading a File Example

This program reads a file entered by the user and displays the content of the file on the output screen. Before running this program, first create any file say "myfile.txt" and writes some content in the file. Here we have written the following content inside this file:

i am a sentence.

Now concentrate on the program given below.

/* C File I/O - Reading a File in C */

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

void main()
{
	FILE *fp;
	char ch, fname[20];
	clrscr();

	printf("Enter filename with extension: ");
	gets(fname);

	fp = fopen(fname, "r");
	if(!fp)
	{
		printf("Error in opening the file..!!");
		exit(1);
	}

	ch = getc(fp);    // read one character

	while(ch != EOF)
	{
		putchar(ch);     // print on the screen
		ch = getc(fp);      // read one character
	}

	fclose(fp);       // close file after use

	getch();
}

Now just enter the filename you have create earlier named "myfile.txt" and press enter. The program will displays the text of the file on the output screen. Here is the sample output of this C program:

c file i/o

C Writing to a File Example

Now the following program ask to the user to enter the filename (with extension like myfile1.txt) to create the file and write some content inside this file entered by the user. To stop the program (writing to a file), simply type '$' and then press enter two times to stop writing to the file and close the program. Here is the program:

/* C File I/O - Writing to a File in C */

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

void main()
{
	FILE *fp;
	char ch, fname[20];
	clrscr();

	printf("Enter the filename to create (with extension): ");
	gets(fname);

	fp = fopen(fname, "w");
	if(!fp)
	{
		printf("Error in opening the file..!!");
		exit(1);
	}

	printf("The file %s is create successfully.\n", fname);
	printf("Now enter some content inside it (type $ to stop writing) :\n");
	do
	{
		ch = getchar();
		putc(ch, fp);
	}while(ch != '$');

	fclose(fp);

	getch();
}

Here is the sample run of this C program:

c reading file

As you can see from the above output, after typing some text, you will find in your BIN folder (for TurboC++ user), a new file named "myfile1.txt" is create and this file contains the text that you have typed in the above program. To check from the program, simply run the program of "C Reading a File Example", and type the file name "myfile1.txt" to read the file. Here is the output:

c writing file

Write and Read the same File in C

Using this C program, you can create a file and write some content inside that file and then reads back all the content written at the time after writing the content on the file. In other word, after writing the content inside the file, when you press ENTER button without entering anything. You will see, all the written content displayed on the screen. And to close the output screen, just press ENTER key again. Here is the program.

/* C File I/O - This program writes some content
 * in the file created by the user, and then
 * reads all the content back from the file to display
 * on the content on the output screen
 */

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

void main()
{
	FILE *fp;
	char str[80];
	char fname[20];
	clrscr();

	printf("Enter a filename to create (with extension): ");
	gets(fname);

	fp = fopen(fname, "w+");
	if(!fp)
	{
		printf("Error in creating the file..!!");
		exit(1);
	}
	printf("The file %s is creted successfully..!!\n", fname);
	do
	{
		printf("Enter a string (CR to quit):\n");
		gets(str);
		strcat(str, "\n");     // adds a newline
		fputs(str, fp);
	}while(*str != '\n');

	// now read and display the file
	rewind(fp);     // reset the file position indicator to start of the file

	while(!feof(fp))
	{
		fgets(str, 79, fp);
		printf(str);
	}

	fclose(fp);
	getch();
}

Here is the sample run of the above C program.

c writing and reading the same file

Deleting a File in C

To delete a file entered by the user, use the function named remove(). Here is its prototype:

int remove(const char *filename);

It returns zero, if the file deleted successfully. Otherwise, it returns a nonzero value. Here is the program.

/* C File I/O - Deleting a File in C */

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

void main()
{
	char fname[20], ch[2];
	clrscr();

	printf("Enter a filename (with extension) to delete: ");
	gets(fname);

	printf("Do you really want to delete this file (Y/N) ?\n");
	gets(ch);

	if(toupper(*ch)=='Y')
	{
		if(remove(fname))
		{
			printf("Error in deleting the file..!!\n");
			exit(1);
		}
		printf("File deleted successfully..!!\n");
	}

	getch();
}

Here is the sample run of the above C program.

c deleting a file

Complete Mailing List Example Program

Here is the complete mailing list example program:

/* C File I/O - This is a simple mailing list
 * example program using an array of structures
 */

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

#define MAX 100

struct address {
	char name[40];
	char street[40];
	char city[30];
	char state[3];
	unsigned long int zip;
} address_list[MAX];

void init_list(void);
void enter(void);
void delet(void);
void list(void);
void load(void);
void save(void);
int menu_select(void);
int find_free(void);

void main()
{
	char choice;
	clrscr();

	init_list();

	for(;;)
	{
		choice = menu_select();
		switch(choice)
		{
			case 1:
				enter();
				break;
			case 2:
				delet();
				break;
			case 3:
				list();
				break;
			case 4:
				save();
				break;
			case 5:
				load();
				break;
			case 6:
				exit(0);
		}
	}

	getch();
}

void init_list(void)
{
	register int i;

	for(i=0; i<MAX; i++)
	{
		address_list[i].name[0] = '\0';
	}
}

int menu_select(void)
{
	char str[80];
	int i;

	printf("1. Enter a name\n");
	printf("2. Delete a file\n");
	printf("3. List the file\n");
	printf("4. Save the file\n");
	printf("5. Load the file\n");
	printf("6. Quit\n");
	do
	{
		printf("\nEnter your choice: ");
		gets(str);
		i = atoi(str);
	}while(i<0 || i>6);

	return i;
}

void enter(void)
{
	int slot;
	char str[80];

	slot = find_free();

	if(slot==1)
	{
		printf("\nList Full..!!");
		return;
	}

	printf("Enter name: ");
	gets(address_list[slot].name);

	printf("Enter street: ");
	gets(address_list[slot].street);

	printf("Enter city: ");
	gets(address_list[slot].city);

	printf("Enter state: ");
	gets(address_list[slot].state);

	printf("Enter zip: ");
	gets(str);
	address_list[slot].zip = strtoul(str, '\0', 10);
}

int find_free(void)
{
	register int i;

	for(i=0; address_list[i].name[0] && i<MAX; i++) ;

	if(i==MAX) return -1;

	return i;
}

void delet(void)
{
	register int slot;
	char str[80];

	printf("Enter record #: ");
	gets(str);
	slot = atoi(str);

	if(slot>=0 && slot<MAX)
	{
		address_list[slot].name[0] = '\0';
	}
}

void list(void)
{
	register int i;

	for(i=0; i<MAX; i++)
	{
		if(address_list[i].name[0])
		{
			printf("%s\n", address_list[i].name);
			printf("%s\n", address_list[i].street);
			printf("%s\n", address_list[i].city);
			printf("%s\n", address_list[i].state);
			printf("%lu\n\n", address_list[i].zip);
		}
	}
	printf("\n\n");
}

void save(void)
{
	FILE *fp;
	register int i;
	char fname[20];

	printf("\nEnter filename to save: ");
	gets(fname);

	if((fp=fopen(fname, "wb")) == NULL)
	{
		printf("Error in opening file..!!\n");
		return;
	}

	for(i=0; i<MAX; i++)
	{
		if(*address_list[i].name)
		{
			if(fwrite(&address_list[i], sizeof(struct address), 1, fp) != 1)
			{
				printf("Error in writing to file..!!\n");
			}
		}
	}

	fclose(fp);
}

void load(void)
{
	FILE *fp;
	register int i;
	char fname[20];

	printf("Enter filename to load: ");
	gets(fname);

	if((fp=fopen(fname, "rb")) == NULL)
	{
		printf("Error in opening the file..!!\n");
		return;
	}

	init_list();
	for(i=0; i<MAX; i++)
	{
		if(fread(&address_list[i], sizeof(struct address), 1, fp) != 1)
		{
			if(feof(fp))
			{
				break;
			}
			printf("Error in reading the file..!!\n");
		}
	}

	fclose(fp);
}

Here is the sample output of the above C program divided into some parts (3 parts here). In the first part, enter your choice (1) to enter the record.

c file handling

Now choose the 3rd option to list the entered record.

c file operation

Now choose the 4th option and then enter the filename to save the record in that file for further uses.

c file input output

More Examples

Here we have listed some more examples that you can go for.


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test