0
while (fgets(line, LINELEN, inputFile)){
      printf("%s$", line)
}

I am trying to read a file and print it out to the console as a CAT command. In this case I wanted to put a dollar sign at the end of every line, but the dollar sigh just happened to print out at the beginning of every line. Could you guys show me how to fix this. Thanks a lot!

stanlopfer
  • 73
  • 1
  • 2
  • 5

2 Answers2

2

fgets includes the '\n' at the end of the line.

Use something like:

char line[hopefullybigenough];
while (fgets(line, sizeof(line), inputFile)) {
    size_t len = strlen(line);
    if (line[len - 1] == '\n') line[len - 1] = '\0';
    printf("%s$\n", line);
}
o11c
  • 15,265
  • 4
  • 50
  • 75
1

The fgets command stores the newline that it read. The usual solution would be to remove the newline (there are several ways to do this of course) . Here is one way:

while (fgets(line, LINELEN, inputFile)) 
{
    strtok(line, "\n");
    printf("%s$\n", line);
}
Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365