File Handling in c: Writing to a file
Posted by Unknown
0
comments
After having learned to read information from a file, now its
time to know how to write to a file.
Now to write to a file we have to obviously create a file
and then open it in write mode. This can be done by a single statement which is
given below
fs=fopen(“abc.txt”,”w”);
Now you may be thinking what the about statement must be doing.
Your answer is right here:
WHAT DOES THE ABOVE STATEMENT DOES?
The above statement does following things:
1.
It creates a new file abc.txt
2.
It opens the file in write mode.
Now let’s take a look at a small program.
Example:
Writing the content of file from “abc.txt” to “xyz.txt”.
Writing the content of file from “abc.txt” to “xyz.txt”.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp,*ft;
char ch;
fp=fopen(“abc.txt”,”r”);
if(fs==NULL)
{
puts(“can’t open source file”);
exit(1);
}
ft=fopen(“xyz.txt”,”w”);
if(ft==NULL)
{
puts(“can’t open target file”);
exit(2);
}
while(1)
{
Ch=fgetc(fp);
If(ch==EOF)
{
break;
}
else
fputc(ch,ft);
}
fclose(fp);
fclose(ft);
}



