Professional Documents
Culture Documents
CPDS Lab Files
CPDS Lab Files
Program 1: Write a C program to copy the content of one file to another file.
#include <stdio.h>
#include <stdlib.h> // For exit()
int main(){
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading");
scanf("%s",filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL){
printf("Cannot open file %s", filename);
exit(0);
}
printf("Enter the filename to open for writing");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL){
printf("Cannot open file %s", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF){
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("Contents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}
Program 2: Write a C Program to Merge the files.
Let the given two files be file1.txt and file2.txt. The following are steps to merge.
1) Open file1.txt and file2.txt in read mode.
2) Open file3.txt in write mode.
3) Run a loop to one-by-one copy characters of file1.txt to file3.txt.
4) Run a loop to one-by-one copy characters of file2.txt to file3.txt.
5) Close all files.
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Open two files to be merged
FILE *fp1 = fopen("file1.txt", "r");
FILE *fp2 = fopen("file2.txt", "r");
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
char ch, fname[30], newch[500];
int i=0, j, COUNT=0;
printf("Enter the filename with extension: ");
gets(fname);
fp = fopen(fname, "r");
if(!fp)
{
printf("Error in opening the file...\nExiting...");
return 0;
}
printf("\nThe original content is:\n\n");
ch = getc(fp);
while(ch != EOF)
{
COUNT++;
putchar(ch);
newch[i] = ch;
i++;
ch = getc(fp);
}
printf("\n\n\n");
printf("The content in reverse order is:\n\n");
for(j=(COUNT-1); j>=0; j--)
{
ch = newch[j];
printf("%c", ch);
}
printf("\n");
return 0;
}