A C program reverses the content of a file

The C program below reverses the content of a file.
input file with content:123456789
output file with the content reversed:987654321
To compile the program: gcc reverse.c
To run the program: ./a.out inputfile.txt

#include <stdio.h>
#include <stdlib.h>

void reverse(FILE *fPtr)
{
  long loc;
  char c1,c2;

  /* find end of source file                                                  
   * store the location to loc, and calculate the middle location*/
  fseek(fPtr, 0L, SEEK_END);
  loc = ftell(fPtr);
  int mid = loc/2;
  //printf("Loc=%d, Size=%d\n",loc,size);                                      

  int i=0;
  loc = loc-1; /* back up past end-of-file mark */
  while(i<mid) {
    /*set the fPtr to appropriate location for c1 and c2,                     
     *and read one byte from that location*/
    fseek(fPtr, i, SEEK_SET);
    fread(&c1,1,1,fPtr);
    fseek(fPtr, loc, SEEK_SET);
    fread(&c2,1,1,fPtr);

    /*se the fPtr to appropriate location, swich c1 with c2*/
    fseek(fPtr, loc, SEEK_SET);
    fwrite(&c1,1,1, fPtr);
    fseek(fPtr, i, SEEK_SET);
    fwrite(&c2,1,1, fPtr);

    --loc;/*from then end,decrement one position in each loop */
    ++i;/*from the beginning, incrememt one position in each loop*/
  }//end of while

  return;
}//end of reverse

int main(int argc, char *argv[])
{
  FILE *fPtr;
 
  /*if the number of arguments is not 2, give error message*/
  if(argc != 2) {
    printf("Usage: ./a.out <filename>.\n");
    exit(1);
  }

  /*if the file cannot be opened, give error message*/
  if((fPtr = fopen(argv[1], "r+")) == NULL) {
    printf("Cannot open input file.\n");
    exit(1);
  }
  reverse(fPtr);
  fclose(fPtr);

  return 0;
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search