Friday, November 18, 2022

BCA and B.Sc Programs - Programming in C Lab - Bharathiar University - Practical Program 11 - C Program to Write a C Program which receives two filenames as arguments and check whether the file contents are same or not. If same delete the second file.

 

Program 11
Write a C Program which receives two filenames as arguments and check whether the file contents are same or not. If same delete the second file.


Source Code
#include <stdio.h>
#include <string.h>
void comparefiles(char filename1[50],char filename2[50]);
int main()
{
char f1[50],f2[50];
    printf("Enter 1st file name: ");
    gets(f1);
    printf("Enter 2nd file name: ");
    gets(f2);
comparefiles(f1,f2);

return 0;
}
void comparefiles(char filename1[50],char filename2[50])
{
FILE* ptr1, *ptr2;
char ch1,ch2;
int flag=1;
// Opening file1 in reading mode
ptr1 = fopen(filename1, "r");
if (ptr1 == NULL) {
printf("file1 can't be opened \n");
}
// Opening file2 in reading mode
ptr2 = fopen(filename2, "r");
if (ptr2 == NULL) {
printf("file2 can't be opened \n");
}
    
// Comparing two files.
do {
ch1 = fgetc(ptr1);
    ch2 = fgetc(ptr2);
    if(ch1!=ch2)
        {
            flag=0;
            break;
        }
  } while (ch1 != EOF || ch2 != EOF);
// Closing the file
    fclose(ptr1);
fclose(ptr2);
    if(flag==1)
    {
    
if(remove(filename2)==0)
    printf("\nContents are same. Second File Deleted successfully");
    else
    printf("\nUnable to delete the file");
    }
else
printf("\nFile Contents are not same");
}



Output


Enter 1st file name: test.txt
Enter 2nd file name: test1.txt
Contents are same. Second File Deleted successfully





No comments:

Post a Comment

Program 12 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 12 Implement a telephone directory using files

  BCA Object Oriented Programming using C++ Practical Madras University  Program 12  Implement a telephone directory using files SOURCE CODE...