Write a C program that reverses the bytes of a given arbitra

Write a C program that reverses the bytes of a given arbitrary length file and outputs them to another specified file, which should be overwritten if it already exists.

So, invoking your program as follows

./reverse infile outfile

will result in the first byte of outfile being the last byte of infile, and so on until the last byte of outfile is the first byte of infile. The given filenames are just an example, make your own infile. You must use fseek()/fread()/fwrite().

Solution

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

int BUFFER_SIZE = 1;

int main (int argc, char *argv[]) {
   unsigned char buffer[BUFFER_SIZE];
   FILE *in, *out;
   int i, n, m;
   unsigned int random;
   if( argc == 3 ){
       in = fopen (argv[1], \"r\");
       out = fopen (argv[2], \"w\");
       fseek(in, 0, SEEK_END); // seek to end of file
       long size = ftell(in);
       for (i = 0; i < size; i++) { //move back 1 at a time
   fread(buffer, 1, sizeof(buffer), in); //read 1 byte
   fwrite(buffer, 1, sizeof(buffer), out); //write 1 byte
   }
   fclose(in);
   fclose(out);
   }
   else if( argc > 3 ){
   printf(\"Too many arguments supplied.\ \");
   }
   else{
   printf(\"Two argument expected.\ \");
   }
   return 0;
}

Write a C program that reverses the bytes of a given arbitrary length file and outputs them to another specified file, which should be overwritten if it already

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site