Showing posts with label File Handling. Show all posts
Showing posts with label File Handling. Show all posts

Saturday, May 14, 2011

Writing and reading strings in files using C Language


C Language also provides fputs() and fgets() functions to handle strings with files.
fputs()
Syntax of fputs() - fputs(< string >, < file pointer >)
fgets()
Syntax of fgets() - fgets(< string >, < max_no_of_characters >, < file pointer >)

Here is a program to demonstrate the use of fputs and fgets function

#include < stdio.h >
#include < string.h >
 void main()
{
FILE *ptr;
char str[80], answer='y';
clrscr();
printf("Program to create a file containing text and then reading the text \n");
ptr=fopen("dd1.txt","w");
while((toupper(answer)) != 'N')
{
printf("Enter the text :");
gets(str);
fflush(stdin);
fputs(str,ptr); /* Writing text (string) into the file */
printf("\n Any more text to add Y/N ?");
scanf("%c", &answer);
printf("\n");
fflush(stdin);
}
printf("Writing of text into the file complete \n");
fclose(ptr);
ptr = fopen("dd1.txt", "r");
printf("The text entered in the file was as follows :\n");
while(!feof(ptr))
{
fgets(str, 80,ptr); /* Reading 80 characters at a time */
printf("%s",str);
}
fclose(ptr);
printf("\nReading of text from the file complete \n\n");
getch();
}

Different C file handling functions for moving around in a file
fseek()
ftell()
rewind()

fseek()
fseek() function in C Language can be used to move forward or backward in a file.
Syntax of fseek() - fseek(< file pointer >, < offset >, < position > );
offsetis the number of bytes we want to move from the current position in the file. position indicates the location in the file from where on wishes to move.
position can take only three values which are
0 - meaning movement from the beginning of the file
1 - meaning movement from the current position in the file
2 - meaning movement from the end of the file.

Different operations of fseek () function

fseek(ptr,0L,0) -  same as rewind () function
 fseek(ptr,m,0)- the pointer moves to the m+1 bytes from the beginning
fseek(ptr,m,1) - pointer moves by m bytes from the current position of the file
fseek(ptr,-m,1) - pointer moves m bytes backward from it's current position
fseek(ptr,-m,2) moves the pointer m bytes backward from the end

ftell()
While reading a file, ftell () function returns the current position of the file in long. The syntax is: ftell (p), while p is the pointer.

rewind()
Syntax of rewind() - rewind(<file pointer>);

Program to demonstrate the above functions

#include < stdio.h >
void main()
{
FILE *ptr;
char str[80];
long int no;
clrscr();
printf("Program to illustrate the use of rewind() function \n\n");
ptr=fopen("dd1.txt","r");
if(ptr== NULL)
{
printf("Can not open the file, terminating .... \n");
getch();
return;
}
printf("The following is the text in the file :\n");
while(!feof(ptr))
{
fgets(str, 80,ptr);
puts(str);
}
printf("The current offset in the file is %ld \n", ftell(ptr));
printf("At this stage, the end of file has been reached, now using rewind() \n");
rewind(ptr);
printf("The following is the text in the file after using rewind() :\n");
while(!feof(ptr))
{
fgets(str,80,ptr);
puts(str);
}
printf("The current offset in the file is %ld \n", ftell(ptr));
fclose(ptr);
getch();
}

Wednesday, April 13, 2011

Use of fscanf function in C File handling


The scanf() function is used for formatted input from the standard input device. In a similar manner the fscanf() function is used for formatted input from files.
Syntax of fscanf() - fscanf(< file pointer >, "< format specifier >", < variable list >)
The following program will create a file and enter some values into the file using fprintf() function. Then the same program will read the values from the file using fscanf() function and will display on the monitor.

#include< stdio.h >
void main()
{
 FILE *ptr;
 int i,number;
 float balance;
 char ch,name[30],filename[10];
 clrscr();
 printf("Enter the file name:-");
 gets(filename);
 ptr=fopen(filename,"w");
 printf("\nEnter data\n");
 printf(" A/c No.  Name  Balance\n");
 for(i=0;i<3;i++)
 {
  fscanf(stdin,"%d%s%f",&number,name,&balance);
  fprintf(ptr,"%4d%10s%6.2f",number,name,balance);
 }
 fclose(ptr);
 ptr=fopen(filename,"r");
 puts(" Number   Name   Balance");
while(!feof(ptr))
 {
  fscanf(ptr,"%d%s%f",&number,name,&balance);
  printf("%4d%10s%6.2f\n",number,name,balance);
 }
 fclose(ptr);
 getch();
 }

Monday, March 28, 2011

Use of fprintf function in C file handling


The printf() function is used for formatted output on the standard output device. In a similar manner the fprintf() function is used for formatted output to files.
Syntax of fprintf() - fprintf(< file pointer >, "< format specifier >", < variable list >)

Program to create a data file using fprintf() function

#include < stdio.h >
void main()
{
FILE *ptr;
int a_no, i,records;
float balance;
char name[30];
clrscr();
printf("Program to create a data file to store information of a bank accounts using fprintf() \n\n");
ptr=fopen("dd.txt","a");
if(ptr == NULL) /* File opened in append mode */
{
printf("Cannot open the file for writing records ... terminating \n\n");
getch();
return;
}
printf("How many records do you want to add :");
scanf("%d", &records);
fflush(stdin);
for(i =0; i < records; i++) /* loop to enter data for number of records */
{
printf("Enter the account number :");
scanf("%d", &a_no);
fflush(stdin);
printf("\n Enter the name of the account holder :");
gets(name);
fflush(stdin);
printf("\n Enter the current balance :");
scanf("%f", &balance);
fflush(stdin);
/* Writing the record in the data file */
fprintf(ptr, "%4d, %30s, %f \n", a_no, name,balance);
} /* End of loop to input number of records */
fclose(ptr);
printf("Writing of records finished \n\n");
getch();
}

Friday, March 11, 2011

Reading from and writing on File in C Programming language


Reading Characters from A file

To read a file character by character, we make use of the getc() standard function available to us.
Syntax of getc() :- <character variable> = getc(<file pointer>);

Writing Characters To A File

To write data into a file character by character, we make use of the putc() standard function in C. putc() function is analogous to the putchar() function already studied.
Syntax of funcyion putc() :- putc(< character variable >, < file pointer >);
Another function which can be used to write data into a file character by character is the fputc() function. fputc() and putc() function both work in exactly the same manner.
Syntax of fputc() :- fputc(< character variable >, < file pointer >);

What is End of File

Any function which enables reading of data from the file will return EOF, when the end of the file has been reached. This implies that reading of data from the file should terminate when EOF if encountered.

Besides, the end of file marker, EOF, 'C' also provides the feof() function, which returns the value true (non zero) if the end of file has been reached or returns false (zero).

Syntax of function feof() :-feof(< file pointer >);
The following program will create a file and value (single line) will be inserted into the file

#include< stdio.h >
 void main ()
 {
 FILE *p;
 char ch;
 printf ("\nNew file is created and write now :-\n");
 p=fopen ("dd1.txt","w");
 while ((ch=getchar ())!='\n')
 putc (ch, p);
/* This function will write the character (first argument) on the buffer.*/
 fclose (p);
 }
getchar () function reads a character from the terminal and putc () function writes it on the file. (Single line can be entered here)

If you want to enter multiple lines then the program will be:

#include< stdio.h >
 void main ()
 {
 FILE *p;
 char ch;
 printf ("\nNew file is created and write now (multiple lines) :-\n");
 p=fopen ("dd1.txt","w");
 while ((ch=getchar ())!=EOF)
 putc (ch, p);
 fclose (p);
 }

In this case after editing the text press ‘Ctrl + Z’ to save the file and Ctrl+Z to generate EOF.




Friday, March 4, 2011

File handling in C Programming Language


Many applications needs to read and write data to disk based storage system. Because all
the data’s of an application are lost when the program is terminated or the computer is turned off. Such information’s are stored in the form of a data file. A file is a place where one can store related data’s permanently. Data files allow us to store information’s permanently and to access and alter the information when required.
C supports a number of functions that are used in file handling.

Naming a file
Opening a file
Reading data from a file
Writing data to a file
Closing a file

There is two type data files: - stream-oriented and system-oriented. Stream-oriented data files are mostly used. When working with a stream-oriented data file, the first step is to establish a buffer area where the data’s will be stored temporarily. The buffer area is established by the statement: FILE *ptr; Here FILE (uppercase is required) is a special structure type defined within stdio.h header file and the pointer ptr points the beginning of the buffer area. A data file must be opened before it can be created or processed. This associates the file name with the buffer area (pointer). It also specifies how the data file will be utilized – read only file, write only file or both. The library function fopen () is used to open a file. This function takes two arguments – the first being the file name as a string and the second argument is the mode as a string in which the file will be opened. The file open mode must be any one of the followings: -

“r”                   Open an existing file for read only

“w”                  Open a new file for writing. If a file with the same            
                                  exists (the name specified as the first argument) then
                                   it will be destroyed and a new file will be created.
      
  “a”                  Open an existing file for appending. If the file does not
                                   exist then a new file will be created.

         “r+”                Open an existing file for both reading and writing

         “w+”              Open a new file for both reading and writing. If the file
                                    exists then the file will be destroyed and a new file
                                    will be created.

         “a+”              Open an existing file for reading and appending. If the
                                    file exists then the file will be destroyed and a new file
                                    will be created.

Functions in 'C' for File Management

fopen()
fclose()
getc()
putc()
fscanf()
fprintf()
fgets()
fputs()
fread()
fwrite()
fseek()
ftell()
feof()
rewind()
fopen()

Subscribe via email

Enter your email address:

Delivered by FeedBurner