Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

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 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");

// Open file to store the result


FILE *fp3 = fopen("file3.txt", "w");
char c;
if (fp1 == NULL || fp2 == NULL || fp3 == NULL)
{
puts("Could not open files");
exit(0);
}
// Copy contents of first file to file3.txt
while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);
// Copy contents of second file to file3.txt
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);
printf("Merged file1.txt and file2.txt into file3.txt");
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;
}

You might also like