1.
/* Program to create a new file(w mode) & write(fputc()) the contents onto the file */
#include<stdio.h>
Int main()
FILE *fp;
char ch;
fp=fopen("xyz.txt","w"); //opens the file in write mode.
if(fp==NULL)
printf("file not found");
while(1)
ch=getchar(); //reads characters from keyboard
if(ch==EOF)
break;
fputc(ch,fp);//writes characters to the file
fclose(fp); //closes the file
2. /*Program to read the contents from a file and display on the screen */
#include<stdio.h>
Int main()
{
FILE *fp;
char ch;
fp=fopen("xyz.txt","r");
if(fp==NULL)
printf("file not found");
while(1)
ch=fgetc(fp);
if(ch==EOF)
break;
putchar(ch);
fclose(fp);
3. /*Program to remove a file*/
#include<stdio.h>
Int main()
FILE *fp;
char fname[20],ch;
puts("enter file name");
gets(fname);
fp=fopen(fname,"r");
if(fp==NULL)
printf("enter the file not found");
fclose(fp);
unlink(fname);
fp=fopen(fname,"r");
if(fp==NULL)
printf("file deleted successfully");
fclose(fp);
return 0;
4. /*Copy the contents of one file to another file
and display the content of destination file*/
#include<stdio.h>
#define size 10
Int main()
FILE *fr=fopen("one.txt","r"); //opens the file in r mode
FILE *fw=fopen("two.txt","w"); //opens 2nd file in w mode
char str[size];
if(fr && fw)
//reading data from 1st file
while(fgets(str,size,fr)!=NULL)
fputs(str,fw);//writing data to 2nd file
fclose(fr);
fclose(fw);
FILE *fp=fopen("two.txt","r");//opens 2nd file
if(fp!=NULL)
char ch=fgetc(fp);
while(ch!=EOF)
printf("%c",ch);
ch=fgetc(fp);
}
return 0;
5. /*file merge*/
/* Program to merge two files into third file*/
#include<stdio.h>
Int main()
{ char c;
FILE *p1=fopen("one.txt","r");//opens 1st file in r mode
FILE *p2=fopen("two.txt","r");//opens 2nd file
FILE *p3=fopen("three.txt","w");//opens 3rd file w mode
while((c=fgetc(p1))!=EOF) //reading from 1st file
fputc(c,p3); //writing to 3rd file
while((c=fgetc(p2))!=EOF) //reading from 2nd file
fputc(c,p3); //writing to 3rd file
fclose(p3); //close 3rd file
fclose(p1); //close 1st file
fclose(p2);//close 2nd file
}
6. //program to demonstrate fseek()
#include<stdio.h>
int main()
FILE *fp;
fp=fopen("demo.txt","w+");
fputs("computers",fp);
fseek(fp,9,SEEK_SET);
fputs("science",fp);
fclose(fp);
return 0;
7. /*Program to demonstrate fseek(), ftell(),rewind() & fputs()*/
#include<stdio.h>
main()
FILE *fp;
fp=fopen("pps.txt","w+");
fputs("welcometoclab",fp);//writes data to a file
fseek(fp,0,SEEK_END);//it will bring the pointer to end of the file content with 0 distance*/
printf("%d\n",ftell(fp));//prints the pointer position.
rewind(fp);//sets the file pointer to the begining of a file
printf("%d",ftell(fp));
fclose(fp);
8. /*Program to demonstrate fprintf() and fscanf()*/
#include<stdio.h>
main()
FILE *fp;
fp=fopen("mid.txt","w+");
int a;
float b;
char ch[20];
printf("enter data");
scanf("%d%f%s",&a,&b,ch);
fprintf(fp,"%d%f%s",a,b,ch);
rewind(fp);
fscanf(fp,"%d%f%s",&a,&b,ch);
printf("after reading from file");
printf("%d%f%s",a,b,ch);
fclose(fp);