Saturday, 5 December 2015

File Handling Programs In C Language

File Management Using C

Prepared By Hitesh Vataliya


One of the difficult work for any one to access the notepad or word file using the c program. But Dennis Ritchie makes it possible for us with the help of fopen() function which is used for connection between our c program and file.
There are many builtin functions for file management in c programming language. Some of them are as below.
fopen() - used to connect with the file, for creating the file or opening the file which was already                        created by using the mode we can open it for 
               r   = reading 
               w = writing
               a  = appending
fclose() - closing the connection with the file after our work is completed.
getc()    - get one character from the file.
putc()    - print one character into the file.
getw()   - get one integer number from the file.
putw()   - Print one integer number into the file.
fscanf() - Scans or take as input one line or string or integer from the file.
fprintf() - Print one line or string or integer to the file.
fseek()   - move the file pointer into the file from begin, current position or end of the file as many                       steps we wants to move the file pointer.
                0 = beginning 
                1 = current position 
                0 = end of the file
 rewind() - move the file pointer to the beginning of the file or 0 th position into the given file.
ftell()     -  returns the position of the file pointer into the given file.

FILE is used for creating file pointer, it acts as a type.


Program 1. Write a program for create a file and insert 3 lines of text into the file.


#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp=fopen("Myfile.txt","w");
fprintf(fp,"Welcome to the VATALIYA TUITION CLASSES\n");
fprintf(fp,"FILE IS CREATED BY HITESH VATALIYA\n");
fprintf(fp,"TODAY IS 4TH DEC,2015");
fclose(fp);
}


Program 2. Write a program for reading a text file which was already created.


#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
fp=fopen("Myfile.txt","r");
c=getc(fp);
while(c!=EOF)
{
printf("%c",c);
c=getc(fp);
}
fclose(fp);
}
          

No comments:

Post a Comment