Powered By Blogger

Friday, April 27, 2012

Program : 17


PROGRAM - 17

a)  Write a program which copies one text file to another.
b)  Write a program to reverse the first N characters of a given text file.

Note: The file name and N are specified through command line.

Program which copies one text file to another file:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<process.h>
void main(int argc,char *argv[])
{
 FILE *fs,*ft;
 char ch;
 clrscr();
 if(argc!=3)
 {
  puts("Invalid number of Arguments:");
  exit(0);
 }
 fs=fopen(argv[1],"r");
  if(fs==NULL)
  {
   puts("Source file cannot be opened");
   exit(0);
  }
  ft=fopen(argv[2],"w");
   if(ft==NULL)
   {
    puts("Target file cannot be opened");
    fclose(fs);
    exit(0);
   }
  while(1)
  {
   ch=fgetc(fs);
    if(ch==EOF)
     break;
    else
     fputc(ch,ft);
  }
  printf("File Copied Successfully.....");
  fclose(fs);
  fclose(ft);
  getch();
}
/*
Sample out:keep all the files including .exe in a same folder copy the source file(Which contain some data) and target file(Which is an empty file) in the same folder and then compile and in cmd prompt set the path where all these files are available give input as
 <filename> <sourcefile> <targetfile>
*/

Program to reverse the first N Charecters of a given text file:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main(int argc,char *argv[])
{
 char a[15],s[20],n;
 int k,j=0,i,len;
 FILE *fp;
 if(argc!=3)
 {
  puts("Invalid no.of argv");
  exit(0);
 }
 fp=fopen(argv[1],"r");
  if(fp==NULL)
  {
   puts("File Cannot be opened");
   exit(0);
  }
  k=*argv[2]-48;
  n=fread(a,1,k,fp);
  a[n]='\0';
  len=strlen(a);
  for(i=len-1;i>=0;i--)
  {
   s[j]=a[i];
   printf("%c",s[j]);
   j=j+1;
  }
  s[j+1]='\0';
  getch();
}

/* Output: Copy all the files in the same folder and for this only source file is enough, the source file should contain same text, then in CMD set the path where all these files are copied and give  <filename> <sourcefile> <no of charecters(in number)> */

No comments:

Post a Comment