-1

I have this small code that is only inverting the text in a file character by character and its working perfectly fine, the problem is that it always adds a '%' at the end.

FILE *fd;

int main (int argc, char *argv[])  {

if ((fd = fopen(argv[1], "r")) != NULL){
    int ft = 0;
    int i = 0;

    fseek(fd, 0, SEEK_END);

    ft = ftell(fd);
    while(i < ft)
    {
        i++;
        fseek(fd, -i, SEEK_END);
        printf("%c", fgetc(fd));
    }
    printf(" ");
    fseek(fd, 0, SEEK_END);

        fclose(fd);
    }

    else {
        perror ("File does not exist !!!\n\a");
    }

    return 0;
}

The input text is : Taco cat

And the output is : tac ocaT %

So i can't find a way to get rid of this pesky % sign. Im in linuxmint.

  • 3
    `perror(argv[1])` is better than `perror("File does not exist!!!")`. Consider the confusion caused by: `"File does not exist!!!: permission denied"` – William Pursell May 27 '22 at 23:53

2 Answers2

6

The % is your shell prompt. It's not from the program. The reason it looks weird is that you forgot to print a \n at the end of the string.

0

For using FILE include <stdio.h> header. checking for file opening can be go outside if statement it makes more readable.

After finish work add a \n to output.

the code so far

#include <stdio.h>

int main(int argc, char *argv[]) {

  FILE *fd = fopen(argv[1], "r");
  if (fd == NULL) {
    perror("File does not exist !!!\n\a");
  }

  int ft = 0;
  int i = 0;

  fseek(fd, 0, SEEK_END);

  ft = ftell(fd);
  while (i < ft) {
    i++;
    fseek(fd, -i, SEEK_END);
    printf("%c", fgetc(fd));
  }
  printf(" ");
  fseek(fd, 0, SEEK_END);

  fclose(fd);
  printf("\n");

  return 0;
}

For more accuracy check result of fseek() which is return zero on success.

Here grab from manpage, man fseek.

RETURN VALUE

   The rewind() function returns no value.  Upon successful completion, fgetpos(), fseek(), fsetpos() re‐
   turn 0, and ftell() returns the current offset.  Otherwise, -1 is returned and errno is set  to  indi‐
   cate the error.
EsmaeelE
  • 2,331
  • 6
  • 22
  • 31