I had a test on C programming today, and this was one of the questions. I got somewhere but wasn't really sure how to get it fully working.
/**********************************************************************
Write a program called 'invert' that inputs an ASCII picture (i.e.
lines of text) from a text file.and prints out the text file
up-side down. Please note that although the example below is quite
small your program should be able to deal with ASCII pictures that
could span very many lines of text.
FOR EXAMPLE: Suppose the text file foo.txt contained the following:
*
***
** **
** ***
** ****
Then the program could work like this:
$ invert foo.txt
** ****
** ***
** **
***
*
There is no one single answer to this problem and a variety of
different solutions may emerge. Please comment your code so that the
marker can gain an insight into the way you are thinking.
You may decide to prompt the user to input the filename or (for
better marks) use a command line argument as in the example.
***********************************************************************/
I came up with something similar to this
Code: Select all
#include <stdio.h>
#include "simpleio.h"
main()
{
char filename[256] = "prog1.c";
char buffer[256];
FILE * file;
file = fopen(filename,"r");
if (file == 0)
{
printf("file %s does not exist\n", filename);
return -1;
}
while (feof(file) == 0)
{
fgets(buffer,256,file);
printf("%s\n", buffer);
}
fclose(file);
}
I was thinking you could use a stack (FILO) but how could you integrate it? something with buffer?
Or am I going in the wrong direction?
There's not much I can do now but I'd like to know what a possible solution could be. Ta.