Originally Posted by
sand_man
You just need to loop through the string backwards displayin each character one at a time instead of using printf("%s",str) to display the whole string
No, no, no... that would print the characters backwards, he wants to print the LINES backwards with each string intact.
Something like this should do it:
Code:
#include <stdio.h>
#include <stdlib.h>
int main () {
// Declare all variables at the beginning.
int i;
FILE *filePointer;
char stringPointers[5][100];
// Open file in read text (rt) mode.
filePointer = fopen ("myfile.dat", "rt");
if (filePointer == NULL) {
printf ("Error opening file: %s\n", "myfile.dat");
exit (1); // Exiting without 0 means there was a problem.
}
// Read 5 lines (up to 99 chars each) and then close the file.
for (i = 0; i < 5; i++) {
fgets (stringPointers[i], 100, filePointer);
}
fclose (filePointer);
// Print in normal order. Linefeeds should be in each string from fgets.
for (i = 0; i < 5; i++) {
printf ("%s", stringPointers[i]);
}
// Print a newline character to separate the outputs.
printf ("\n");
// Print in reverse order.
for (i = 4; i >= 0; i--) {
printf ("%s", stringPointers[i]);
}
return 0;
}
Or with dynamic allocation:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int main () {
// Declare all variables at the beginning.
int i;
FILE *filePointer;
char **stringPointers;
// Allocate the array of 5 strings.
// This is a pointer to pointers (works as char[][]).
stringPointers = (char **) malloc (5 * sizeof (char *));
// Allocate each string (up to 99 chars in length each).
// This is a pointer to characters (works as char[]).
for (i = 0; i < 5; i++) {
stringPointers[i] = (char *) malloc (100);
}
// Open file in read text (rt) mode.
filePointer = fopen ("myfile.dat", "rt");
if (filePointer == NULL) {
printf ("Error opening file: %s\n", "myfile.dat");
exit (1); // Exiting without 0 means there was a problem.
}
// Read 5 lines (up to 99 chars each) and then close the file.
for (i = 0; i < 5; i++) {
fgets (stringPointers[i], 100, filePointer);
}
fclose (filePointer);
// Print in normal order. Linefeeds should be in each string from fgets.
for (i = 0; i < 5; i++) {
printf ("%s", stringPointers[i]);
}
// Print a newline character to separate the outputs.
printf ("\n");
// Print in reverse order.
for (i = 4; i >= 0; i--) {
printf ("%s", stringPointers[i]);
}
// Clean up memory that was allocated with malloc (good habit).
for (i = 0; i < 5; i++) {
free (stringPointers[i]);
}
free (stringPointers);
return 0;
}