-2

I am trying to read and print from another file and reverse every line separately but I am only able to print out the lines and reverse the last line. Any suggestions on what I need to do to reverse every line in the file? *I cannot use strrev(), must keep its same format but reversed (i.e same capitalization, numbers, and symbols)

int main() {
    int i=0, j, len;
    char data[80]. rev[];
    FILE *fp = fopen("fileread", "r");
                               // reads and prints out fileread
    while(!feof(fp))){
        fgets(data, 80, fp);
        puts(data);
    }
                    // reverse hopefully
    while(data[++i] != '\0;);
    while(i>=0);
    rev[j++] = data[--j];
    rev[j] = '\0';
    printf("String Reversed: %s\n, rev);
    fclose(fp0);
}

here is an example of what I want.

(file text)

Hello World!
I am $till around.
running @ Best Speedz
kayak

expected output:

!dlroW olleH 
.dnuora llit$ ma I
zdeepS tseB @ gninnur
kayak
Barmar
  • 741,623
  • 53
  • 500
  • 612
lulu smith
  • 15
  • 2
  • please post code in your question, not as image or whatever. – Jean-François Fabre Mar 27 '17 at 18:50
  • No no no. The code belongs *inside* the question. Post a [mcve]. – StoryTeller - Unslander Monica Mar 27 '17 at 18:50
  • Please see [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). Better something like `while(fgets(data, sizeof data, fp) != NULL) {...}`. And watch out for the `newline` retained by `fgets` at the end of the `data` string. – Weather Vane Mar 27 '17 at 18:52
  • The edit is not the same code as the image. I was about to comment that the loop increments `i` and then decrements `i` but you have changed that to ditto with `j`. Please post the [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) that shows the problem. – Weather Vane Mar 27 '17 at 18:58

1 Answers1

0

The code to print the reversed line is outside the while loop. Hence it will only print the last line.

In the while loop, test for fgets(...)!=NULL.

Don't forget to remove the newline at the end of the line if it is there, or you'll have a surprise when you reverse the string.

Finally, for readability, create a separate function to perform an in-place reverse of a string.

  • Thank you! I could not get this section of my code, but changing it to the NULL statement really helped a lot! – lulu smith Mar 31 '17 at 03:28