Thursday 13 September 2012

To reverse the first n characters in a file


Description:
                  This program perform the reverse operation of  n characters in the file
Algorithm:
Step 1: Star
Step 2: read the command line arguments
Step 3: check if arguments=3 or not
                           If not print invalid no of arguments
Step 4: open source file in read mode
Step 5: if NULL pointer, then print file can not be open
Step 6: Store no of chars to reverse in k
                     K= *argv[2]-48
Step 7: read the item from file stream using fread
Step 8: Store chars from last position to initial position in another string(temp)
Step 9: print the temp string
Step 10: Stop
Program:

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <process.h>

void main(int argc, char *argv[])
{
  char a[15];
  char s[20];
  char n;
  int k;
  int j=0;
  int i;
  int len;
  FILE *fp;

  if(argc!=3)
  {
            puts("Improper number of arguments.");
             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:
source.c
           this is source
ouput.c

Command line arguments
source.c ouput.c
source.c
           this is source

           ecruos si siht

Command line arguments
source.c
Invalid number of arguments.

Conclusion: the program is error free


VIVA QUESATIONS:
1) List out the file handling functions ?
Ans: fopen(), fprintf(),fclose(),fscanf(),fgetc(),fputc(), etc..,

2) What is the use of  fseek() function ?
Ans: The function fseek sets the file pointer associated with a stream to a new position

3) What is use of the fflush() function ?
Ans:  If the given stream has a buffered output, fflush writes the output of the stream to the associate file.









1 comment:

  1. k=*argv[2]-48;
    what is happening here? why this 48 is reduced? i know something that is related to memory of disk. please explain me.could not understand.

    ReplyDelete