errorcodemonkey
errorcodemonkey

Reputation: 382

Avoiding adding a new line at the end of file

Given the code reading from the standard input



    int main() {
         int c;
         while ((c = getchar()) != EOF) {
              fprintf(stdout, "%c", c);
         }
    }

This code is fine for reading all contents from the stdin containing multiple lines. But it will add a new line at the end of file. How can I modify the above code so that I can prevent from adding an extra new line \n in the last line of stdin? The example of stdin is given below.


hello world!!!
how is going today?
this is the last line in stdin

Upvotes: 1

Views: 1567

Answers (1)

HAL9000
HAL9000

Reputation: 2188

As @NateEldredge said in a friendly way, removing the trailing '\n' from the last line is dumb. By convention, on UNIX-like systems, every line in a textfile must be terminated with '\n'. But if you actually want to remove the last newline, maybe to be compatible with some lesser OS, you have to delay printing of characters until you know if the next read returned EOF, or not:

#include <stdio.h>

int main(void)
{
  int c = getchar();
  int peek_c;
  if (c != EOF)
    {
      /* Print out everything except the last char */
      while ((peek_c = getchar()) != EOF)
        {
          fprintf(stdout, "%c", c);
          c = peek_c; 
        }
      /* If the last char was not '\n', we print it
         (We only want to strip the last char if it is a newline)  */
      if (c != '\n')
         fprintf(stdout, "%c", c);
    } 
}

Upvotes: 1

Related Questions