避免在文件末尾添加新行

时间:2020-06-28 22:52:23

标签: c printf getchar

从标准输入中读取代码



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

此代码适合从stdin中读取包含多行的所有内容。但是它将在文件末尾添加新行。如何修改上面的代码,以防止在\n的最后一行添加额外的新行stdin?以下是stdin的示例。


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

1 个答案:

答案 0 :(得分:1)

正如@NateEldredge友好地说道,从最后一行删除结尾的'\n'是愚蠢的。按照惯例,在类似UNIX的系统上,文本文件中的每一行都必须以'\n'结尾。但是,如果您实际上想删除最后一个换行符(也许是为了与某些较小的OS兼容),则必须延迟打印字符,直到知道下一个读取是否返回EOF为止:

#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);
    } 
}