Friday, November 21, 2014

C File pro



Program to copy the contents of one file into another using fgetc and fputc function


#include
#include
#include
 void main()
{
   FILE *fp1, *fp2;
   char a;
   clrscr();
   fp1 = fopen("test.txt", "r");
   if (fp1 == NULL)
   {
      puts("cannot open this file");
      exit(1);
   }
   fp2 = fopen("test1.txt", "w");
   if (fp2 == NULL)
     {
      puts("Not able to open this file");
      fclose(fp1);
      exit(1);
   }
   do
     {
      a = fgetc(fp1);
      fputc(a, fp2);
   }
   while (a != EOF);
   fcloseall();
   getch();
}

Output


Content will be written successfully to file

Write a C program to read last n chatacters of the file using appropriate file function


#include
#include 
int main()
{
   FILE *fp;
   char ch;
   int num;
   long length;

   printf("Enter the value of num : ");
   scanf("%d", &num);
   fp = fopen("test.txt", "r");
   if (fp == NULL)
   {
      puts("cannot open this file");
      exit(1);
   }
   fseek(fp, 0, SEEK_END);
   length = ftell(fp);
   fseek(fp, (length - num), SEEK_SET);
    do
   {
      ch = fgetc(fp);
      putchar(ch);
   } while (ch != EOF);
   fclose(fp);
   return(0);
}

Output


Enter the value of n : 4
.com 

Compare two files in a C Programming


#include
#include
int main()
 {
   FILE *fp1, *fp2;
   int ch1, ch2;
   char fname1[40], fname2[40];
   printf("Enter name of first file :");
   gets(fname1);
   printf("Enter name of second file:");
   gets(fname2);
   fp1 = fopen(fname1, "r");
   fp2 = fopen(fname2, "r");
   if (fp1 == NULL)
  {
      printf("Cannot open %s for reading ", fname1);
      exit(1);
      }
      else if (fp2 == NULL)
      {
      printf("Cannot open %s for reading ", fname2);
      exit(1);
    }
    else
    {
      ch1 = getc(fp1);
      ch2 = getc(fp2);
       while ((ch1 != EOF) && (ch2 != EOF) && (ch1 == ch2)) {
         ch1 = getc(fp1);
         ch2 = getc(fp2);
      }
      if (ch1 == ch2)
         printf("Files are identical n");
      else if (ch1 != ch2)
         printf("Files are Not identical n");
       fclose(fp1);
      fclose(fp2);
   }
   return (0);
}

Copy Text From One File to Other File


#include
#include
#include
void main()
{
   FILE *fp1, *fp2;
   char ch;
   clrscr();
   fp1 = fopen("Sample.txt", "r");
   fp2 = fopen("Output.txt", "w");
    while (1)
    {
      ch = fgetc(fp1);
       if (ch == EOF)
         break;
      else
         putc(ch, fp2);
   }
    printf("File copied Successfully!");
   fclose(fp1);
   fclose(fp2);
}

No comments:

Post a Comment