Search code examples
cquine

How to Reverse Quine?


i have written a C programme which prints itself n times, but i can't get how to reverse print the same n times.E.g, if the sample programme is :

hello

then the required output should be "olleh" for n=1. Here's my quine programme,

#include <stdio.h>
int main()
{
  int n;
  char c;
  FILE *f;
  f=fopen(__FILE__,"r");
  scanf("%d",&n);
 while(n--)
 {
 while((c=getc(f))!=EOF)
 putchar(c);
 fseek(f,0,0);
 }
  return 0;
} 

Solution

  • The easiest way would be to read the file into an array (like this answer), and then just reverse the array:

    void swap(char* a, char* b) {
      char tmp = *b;
      *b = *a;
      *a = tmp;
    }
    
    void reverse(char* arr, int size) {
      for (int i = 0; i < size/2; ++i) {
        swap(arr+i, arr + (size - (i + 1)));
      }
    }