C Language

Filing in C

In C Language by Baqir AliLeave a Comment

Most programs need to read and write data to disk based storage systems. Word processor need to store text files, spreadsheets need to store the contents of cells and databases need to store records. Disk I/O operations are performed on entities called files. A file is a collection of byte that is given a name. In most microcomputer system, files are used as unit of storage primarily on floppy disk or hard disk or other storage devices.

Accessing Files

Files can be thought of as a stream of characters. Files have several important properties.

  • They have a name
  • They must be opened and closed.
  • They can be written to, or red from, or appended to.

To define a pointer to a file:

FILE *file_name;
#include <stdio.h>
int main(void)
{
	FILE *ifp, *ofp;
	ifp = fopen(“file1.txt”, “r”);
	ofp = fopen(“file2.txt”, “w”);
	…

This opens two files in the current directory: file1.txt for reading and file2.txt for writing.

Suppose file1.txt contains integers. To sum them and put the result in file2.txt

int val, sum=0;
while (fscanf(ifp,“%d”,&val) == 1)
        sum += val;
	fprintf(ofp,“The sum is %d.\n”,sum);

After the files are finished being used, they can be closed by writing

fclose(ifp);
fclose(ofp);

fopen()

A function call of the form

fopen(file_name, mode)

opens the named file in a particular mode and returns a file pointer.

“r” open text file for reading, File must already exist
“w” Open for writing/creation, if file already exist it data will be overwrite.
“a” Open for append, data will be added in already exist file.
“rb” open binary file for reading
“wb” open binary file for writing
ab open binary file for appending

The first three modes can end with a + character. This means the file is to be opened for both reading and writing.

fclose()

A function call of the form

fclose(file_name)

closes the named file. If the file is successfully closed, zero is returned.

The functions fprintf() and fscanf()

The functions fprintf() and fscanf() are file versions of the functions printf() and scanf() respectively.

fprintf();

A call to this function takes the general form

fprintf(fp, format_string, arg1, arg2, …)

where

  • fp is the pointer to a file
  • format_string refers to a character string containing certain required formatting information
  • arg1, arg2, etc., are arguments that represent the individual input data items.

fscanf();

A call to this function takes the general form

fscanf(fp, format_string, &arg1,&arg2,…)

where

  • fpis the pointer to a file
  • format_string refers to a character string containing certain required formatting information
  • arg1, arg2, etc., are arguments that represent the individual input data items.

Leave a Comment