Lab Programs using File Operations in C:
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 [Link] and [Link]. The following are steps to merge.
1) Open [Link] and [Link] in read mode.
2) Open [Link] in write mode.
3) Run a loop to one-by-one copy characters of [Link] to [Link].
4) Run a loop to one-by-one copy characters of [Link] to [Link].
5) Close all files.
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Open two files to be merged
FILE *fp1 = fopen("[Link]", "r");
FILE *fp2 = fopen("[Link]", "r");
// Open file to store the result
FILE *fp3 = fopen("[Link]", "w");
char c;
if (fp1 == NULL || fp2 == NULL || fp3 == NULL)
{
puts("Could not open files");
exit(0);
}
// Copy contents of first file to [Link]
while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);
// Copy contents of second file to [Link]
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);
printf("Merged [Link] and [Link] into [Link]");
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}
Program 3: Write a program in C that displays the content of a file in reverse order. The
filename should be entered at run-time .
#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;
}