Exforsys.com
 
Home Tutorials C Language
 

C Programming - File management in C

 

C Programming - File management in C

In this tutorial you will learn about C Programming - File management in C, File operation functions in C, Defining and opening a file, Closing a file, The getw and putw functions, The fprintf & fscanf functions, Random access to files and fseek function.



C supports a number of functions that have the ability to perform basic file operations, which include:
1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file


  • Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two major problems
  • It becomes cumbersome and time consuming to handle large volumes of data through terminals.
  • The entire data is lost when either the program is terminated or computer is turned off therefore it is necessary to have more flexible approach where data can be stored on the disks and read whenever necessary, without destroying the data. This method employs the concept of files to store data.

File operation functions in C:

Function Name


Operation


fopen()


Creates a new file for use
Opens a new existing file for use


fclose


Closes a file which has been opened for use


getc()


Reads a character from a file


putc()


Writes a character to a file


fprintf()


Writes a set of data values to a file


fscanf()


Reads a set of data values from a file


getw()


Reads a integer from a file


putw()


Writes an integer to the file


fseek()


Sets the position to a desired point in the file


ftell()


Gives the current position in the file


rewind()


Sets the position to the begining of the file


Defining and opening a file:

If we want to store data in a file into the secondary memory, we must specify certain things about the file to the operating system. They include the fielname, data structure, purpose.


The general format of the function used for opening a file is


FILE *fp;
fp=fopen(“filename”,”mode”);

The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier, File is a structure that is defined in the I/O Library. The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp. This pointer, which contains all the information about the file, is subsequently used as a communication link between the system and the program.
The second statement also specifies the purpose of opening the file. The mode does this job.

R open the file for read only.
W open the file for writing only.
A open the file for appending data to it.

Consider the following statements:


FILE *p1, *p2;
p1=fopen(“data”,”r”);
p2=fopen(“results”,”w”);


In these statements the p1 and p2 are created and assigned to open the files data and results respectively the file data is opened for reading and result is opened for writing. In case the results file already exists, its contents are deleted and the files are opened as a new file. If data file does not exist error will occur.


Closing a file:

The input output library supports the function to close a file; it is in the following format.
fclose(file_pointer);

A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer.
Observe the following program.


….
FILE *p1 *p2;
p1=fopen (“Input”,”w”);
p2=fopen (“Output”,”r”);
….

fclose(p1);
fclose(p2)


The above program opens two files and closes them after all operations on them are completed, once a file is closed its file pointer can be reversed on other file.

The getc and putc functions are analogous to getchar and putchar functions and handle one character at a time. The putc function writes the character contained in character variable c to the file associated with the pointer fp1. ex putc(c,fp1); similarly getc function is used to read a character from a file that has been open in read mode. c=getc(fp2).


The program shown below displays use of a file operations. The data enter through the keyboard and the program writes it. Character by character, to the file input. The end of the data is indicated by entering an EOF character, which is control-z. the file input is closed at this signal.

#include< stdio.h >
main()
{
file *f1;
printf(“Data input output”);
f1=fopen(“Input”,”w”); /*Open the file Input*/
while((c=getchar())!=EOF) /*get a character from key board*/
putc(c,f1); /*write a character to input*/
fclose(f1); /*close the file input*/
printf(“\nData output\n”);
f1=fopen(“INPUT”,”r”); /*Reopen the file input*/
while((c=getc(f1))!=EOF)
printf(“%c”,c);
fclose(f1);
}


The getw and putw functions:

These are integer-oriented functions. They are similar to get c and putc functions and are used to read and write integer values. These functions would be usefull when we deal with only integer data. The general forms of getw and putw are:


putw(integer,fp);
getw(fp);


/*Example program for using getw and putw functions*/
#include< stdio.h >
main()
{
FILE *f1,*f2,*f3;
int number I;
printf(“Contents of the data file\n\n”);
f1=fopen(“DATA”,”W”);
for(I=1;I< 30;I++)
{
scanf(“%d”,&number);
if(number==-1)
break;
putw(number,f1);
}
fclose(f1);
f1=fopen(“DATA”,”r”);
f2=fopen(“ODD”,”w”);
f3=fopen(“EVEN”,”w”);
while((number=getw(f1))!=EOF)/* Read from data file*/
{
if(number%2==0)
putw(number,f3);/*Write to even file*/
else
putw(number,f2);/*write to odd file*/
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen(“ODD”,”r”);
f3=fopen(“EVEN”,”r”);
printf(“\n\nContents of the odd file\n\n”);
while(number=getw(f2))!=EOF)
printf(“%d%d”,number);
printf(“\n\nContents of the even file”);
while(number=getw(f3))!=EOF)
printf(“%d”,number);
fclose(f2);
fclose(f3);
}


The fprintf & fscanf functions:

The fprintf and scanf functions are identical to printf and scanf functions except that they work on files. The first argument of theses functions is a file pointer which specifies the file to be used. The general form of fprintf is


fprintf(fp,”control string”, list);


Where fp id a file pointer associated with a file that has been opened for writing. The control string is file output specifications list may include variable, constant and string.


fprintf(f1,%s%d%f”,name,age,7.5);


Here name is an array variable of type char and age is an int variable
The general format of fscanf is


fscanf(fp,”controlstring”,list);


This statement would cause the reading of items in the control string.

Example:

fscanf(f2,”5s%d”,item,&quantity”);


Like scanf, fscanf also returns the number of items that are successfully read.

/*Program to handle mixed data types*/
#include< stdio.h >
main()
{
FILE *fp;
int num,qty,I;
float price,value;
char item[10],filename[10];
printf(“Input filename”);
scanf(“%s”,filename);
fp=fopen(filename,”w”);
printf(“Input inventory data\n\n”0;
printf(“Item namem number price quantity\n”);
for I=1;I< =3;I++)
{
fscanf(stdin,”%s%d%f%d”,item,&number,&price,&quality);
fprintf(fp,”%s%d%f%d”,itemnumber,price,quality);
}
fclose (fp);
fprintf(stdout,”\n\n”);
fp=fopen(filename,”r”);
printf(“Item name number price quantity value”);
for(I=1;I< =3;I++)
{
fscanf(fp,”%s%d%f%d”,item,&number,&prince,&quality);
value=price*quantity”);
fprintf(“stdout,”%s%d%f%d%d\n”,item,number,price,quantity,value);
}
fclose(fp);
}


Random access to files:

Sometimes it is required to access only a particular part of the and not the complete file. This can be accomplished by using the following function:


1 > fseek


fseek function:

The general format of fseek function is a s follows:


fseek(file pointer,offset, position);


This function is used to move the file position to a desired location within the file. Fileptr
is a pointer to the file concerned. Offset is a number or variable of type long, and position in an integer number. Offset specifies the number of positions (bytes) to be moved from the location specified bt the position. The position can take the 3 values.


Value Meaning
0 Beginning of the file
1 Current position
2 End of the file.



Read Next: C Language - The Preprocessor



 

 

Comments


Deep Xavier T. Duites said:

  This topic is helpful but there are some typographical errors (function names, function prototypes, omitted commas & semicolons) I had observed. These errors might lead to confusion and misinformation to the reader.
July 12, 2006, 3:51 am

ramakrishh said:

  Illustrative examples were used so that it became very easy to understand.Keep on adding new examples.
December 15, 2006, 3:35 am

size of progarm said:

  who to manage in the size of program if i need to do the size like the size of floppy disc what i need to do
April 21, 2007, 8:56 am

Lynette said:

  This information is helpful, however it did not solve my problem. How do you find the location of the file that you are trying to open using fptr=fopen(File???, "r")? And, when trying to open a program in C, is it necessary that the other program be a C file as well? And if in fact the other program is not in C format, how can you change it to make it readable to C without changing any of the content?
July 13, 2007, 10:50 am

sajad said:

  I want to compile my data in C but my data is in excel format(microsoft office).
but i can't. please help me
August 9, 2007, 6:39 pm

tyhods said:

  If your data is in an excel file, just save the excel file as a tab delimited text file. Then you should be able to access the data from the file in C.
If you have the data in C, you save your text file as a tab delimited text file. Then you can open that text file in excel and convert the data to excel format.
November 24, 2007, 2:42 am

L said:

  I am programming in c, and the program should ask to enter a word. A file with 10 strings should be searched to match the word entered. If the word matches the string it should be printed. What function could I use to match the key word to a string in a file?
December 10, 2007, 3:29 pm

Scooter said:

  Can anybody tell me how to count the paragraphs of a file, of which name, is entered by the user in a command line program using argc, argv etc?
December 13, 2007, 3:32 am

Chirag...... said:

  Would you tell me why ftell() returns 0 in a file that is opened in append mode?
April 11, 2008, 12:15 am

Maneesh Agarwal said:

  I'm having file having similar data
$GPGGA,230611.016,3907.3813,N,12102.4635,W,0,04,5.7,507.9,M,,,,0000*11
$GPRMC,230611.016,V,3907.3813,N,12102.4635,W,0.14,136.40,041002,,*04
$GPGGA,230612.015,3907.3815,N,12102.4634,W,0,04,5.7,508.3,M,,,,0000*13
$GPGGA,171538,3350.974,N,11823.991,W,2,07,1.1,-25.8,M,,M,1.8,,D*19
$GPRMC,171537,A,3350.975,N,11823.991,W,0.0,096.5,060401,013.0,E,D*07
$GPGGA,120557.916,5058.7456,N,00647.0515,E,2,06,1.7,108.5,M,47.6,M,1.5,0000*7A
$GPGGA,120558.916,5058.7457,N,00647.0514,E,2,06,1.7,109.0,M,47.6,M,1.5,0000*71

The first word in the line is either $GPGGA or $GPRMC. The data is redirected to the file and gets appended. Based on the requirement, I do need to read the latest line having $GPGGA or $GPRMC. How can I do it?
July 10, 2008, 11:54 pm

nisha said:

  give me detail example of file management please .....
November 18, 2008, 12:03 am

rohit afterglow said:

  a lot information missing then also it is very good then others till i find topics on file handling .well done
November 25, 2008, 7:23 am

Sangi1987 said:

  Need a C program that would reads the file and builds a linked list. After the list is built, display it on the monitor
November 27, 2008, 8:31 am

0 said:

  I wrote a C program for micro controller and I also added the file system into the program, but the program cannot be downloaded into the micro controller, is there any way to solve it?
January 13, 2009, 10:21 pm

SAWAN CHOUREY said:

  I am read this page thanks for giving this information
January 20, 2009, 2:53 pm

JITESH said:

  How to open a word document in C language.... Can u post the code for this???
January 24, 2009, 12:20 am

anilgodawat said:

  How to open a word document in C language.... Can u post the code for this???
February 7, 2009, 10:48 pm

anilgodawat said:

  difference between ;
getc and getchar
printf and fprintf
feof and ferror
plz give datail difference between those
February 7, 2009, 10:52 pm

naresh said:

  printf function is used to display data on the screen. but using fprintf we can print data directly into a file not on the screen.

feof function used to check whether the end of the file has been reached or not.

ferror function is used to identify, whether any error in program exists or not. for example, you had opened a file in an reading mode, but you are trying to access in writing mode ok.
March 18, 2009, 2:13 am

nandini said:

  I am writing a program in C. I want to know how to open excel files in C. How to load excel files in C. Because basically my program deals with comparison with two excel files. The problem I am facing is I am not able to open the files and compare. Can you suggest me any solution.
March 24, 2009, 11:33 pm

MadhuMohan Reddy U.V said:

  When I am working with malloc I got different doubt which is given bellow

int *ptr;
ptr=(int*)malloc(0);
Which gives valid address but my doubt is how compiler find out the size? and how it give valid address?
April 14, 2009, 6:10 am

Dhivyabala said:

  I just want to know how to retrieve details from the file, modify then store.
April 15, 2009, 2:26 pm

mduduzi said:

  I want to know how to use data in excel to perform calculation in C programming code.
May 7, 2009, 5:50 am

bikram said:

  How does the compiler identifies the different variable of the same data type?
August 24, 2009, 6:22 am

rajesh said:

  why offset should be long in fseek
August 31, 2009, 6:52 am

sharath said:

  @bikram,

different variables will be stored in a table called the symbol table by the compiler . symbol table will have the following entities :
a) variable name
b) its starting address
c) its datatype

the above is true only in case of global variable.

In case of locals, the variables are dynamically created in stack and are wiped out immediately after the context of the variable is exited.

September 18, 2009, 10:59 am

Santhosh said:

  Hi,
I have to write some details to a file using C in Unix.While writting, how to stop others from seeing the file(or others should not have the write permission).Help me friends.
October 8, 2009, 10:28 am

Lopamudra said:

  I want to read an image file from the 5th line upto the end and store the 256X256 matrix in a 2D array.

How can I do that?Is there any prototype command which helps me to start reading the file from the 5th line?
October 26, 2009, 12:50 am

kalshanm said:

  I want to read values from the external file and use those values in another C file. Like using properties file in Java and perl. How to do this C ?
November 9, 2009, 5:03 am

patel said:

  Hi
I want to open SQL table in my C program How can I open SQL table in C language and also read data from sales table.
November 12, 2009, 11:48 pm

Post Your Comment:

Members Please Login
Your Name:*
e-mail ID:(required for notification)*
Image Verification: 
 
 Subscribe    

Sponsored Links

 

Subscribe via RSS


Get Daily Updates via Subscribe to Exforsys Free Training via email


Get Latest Free Training Updates delivered directly to your Inbox...

Enter your email address:


 

Subscribe to Exforsys Free Training via RSS
 

 
Partners -  Privacy and Legal Policy -  Site News -  Contact   Sitemap  

Copyright © 2000 - 2009 exforsys.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape