A file can be defined as a location on the disk where we
store logically related data under a same name
In c programming we
can make file in which we can store and retrieve data
Before writing data to a file we first have to define a file
and we do this by using the following syntax
FILE *fp ;
Fp = fopen(“file
name”,”mode”) ;
In the first line of the syntax we declare a pointer “*fp”
which is of FILE type , it is a special type which handles files
Now we use this pointer to open a file , this is very
important , weather we want to read or write to a file we first have to open it
and we do this by using “fopen” which means “file open”
fopen takes two parameter , one is the file name and other
is the mode . Mode can be read , write or append which is represented by
keywords “r” , “w” , “a”
after we open the file , we can manipulate the file and then
we close the file . Closing of the file is done by writing
fclose( fp ) ;
let us now see a program which creates a file and writes
characters to it
#include<stdio.h>
main()
{
FILE *fp;
char c;
printf("Enter
Data\nTo finish writing press enter then type ctrl + z to end\n\n");
fp =
fopen("f:\\file one.txt","w");
while((c=getchar())!=EOF)
{
putc(c,fp);
}
fclose(fp);
printf("Press
Enter To Exit\n");
getch();
}
We have seen how to write characters to a file , now let us
see how we can read data from a file we have created
#include<stdio.h>
main()
{
FILE *fp;
char c;
printf("The
Contents Of The File\n\n");
fp =
fopen("f:\\file one.txt","r");
while((c = getc(fp))
!= EOF)
{
printf("%c",c);
}
fclose(fp);
getch();
}
Soon going to update more
No comments:
Post a Comment