I've got a C program that I'm trying to write which intends to reverse the lines of a file. I am still very inept at C (though I come from a Java background), so I am very likely making mistakes with pointers and such, but I've tried consulting the manual at every turn. This is somewhat of an assignment.
The point of the program is to reverse a file's contents, up to MAX_LINES in number, each line being no longer than MAX_CHARS. The method I wanted to try is the following: use fgets to read from the file, 80 chars or until EOL, store that string, and repeat the process until either EOF or MAX_LINES has been reached, using a counter on the side. Afterwards I simply put the same string in a different array, going from second_array[counter] to 0. However, I am having issues with actually getting the strings into the first array. Here's what I have so far:
1 #include <stdio.h>
2 #include <string.h>
3
4 #define MAX_LINES 100
5 #define MAX_CHAR 80
6
7 int main(int argc, char *argv[])
8 {
9 if(argc != 2)
10 goto out;
11 FILE *fp;
12 char *str[MAX_CHAR];
13 char buffer[MAX_CHAR];
14 char *revstr[MAX_CHAR];
15 int curr_line = 0, i = 0, j =0;
16
17 fp = fopen(argv[1],"r");
18
19 out:
20 if (fp == NULL && argc != 2){
21 printf("File cannot be found or read failed.\n");
22 return -1;
23 }
24
25 /* printf("This part of the program reverses the input text file, up to a maximum of 100 lines and 80 characters per line.\n The reversed file, from the last (or 100th) line to the first, is the following:\n\n"); */
26
27 /* fgets reads one line at a time, until 80 chars, EOL or EOF */
28 while(curr_line < MAX_LINES && ((fgets(buffer, MAX_CHAR, fp)) != NULL)){
29
30 str[i] = buffer;
31 ++j;
32 ++i;
33 }
34
35 for(i = 0; i < 4; ++i)
36 printf("%s \n", str[i]);
37
38
39 printf("END OF PROGRAM RUN.");
40 return 0;
41 }
In the same directory, I have a "txt" file which contains the following lines:
is this a test
this is a test
this is not a test
When I compile and run the program however (./a.out txt), I get the following output:
this is not a test
this is not a test
this is not a test
END OF PROGRAM RUN.
Obviously this means that is is overwriting the same location, but I am not sure how to rectify this (as said, pointers are still pretty alien to me). Could anyone clarify what is happening here? Do I need to use a 2D array instead? Any help would be greatly appreciated.