【问题标题】:how to print line numbers from multiple files without using fgets如何在不使用 fgets 的情况下从多个文件中打印行号
【发布时间】:2022-01-10 23:17:05
【问题描述】:

我正在尝试在不使用fgets()的情况下在行首打印行号 是的,当我输入多个文件时,它可以很好地打印行号 但我想得到这样的结果。你们能帮我解决这个问题吗?

现在结果

1 I'll always remember
2 the day we kiss my lips
3
4 light as a feather
*5 ####@localhost ~ $*

期待结果

1 I'll always remember
2 the day we kiss my lips
3
4 light as a feather
*####@localhost ~$*

这是我的代码:

#include <stdio.h>

int main(int argc, char *argv[]) {
    FILE *fp;
    int c, n;
    n = 1;
    for (int i = 1; i < argc; i++) {
        if (argc < 2) 
            fp = stdin; 
        else
            fp = fopen(argv[i], "r"); 
        c = getc(fp); 
        printf("%d ", n);
        while (c != EOF) { 
            putc(c, stdout); 
            if (c == '\n')
                n++, printf("%d ", n);
            c = getc(fp);
        }
        fclose(fp);
    }
    return 0;
}

【问题讨论】:

  • 将文本作为文本发布更有用。

标签: c fgetc putchar


【解决方案1】:

不知道有没有下一行的时候不要写printf("%d ", n);。或者,否则,仅在文件开头和换行符之后执行printf("%d ", n);,当您知道有下一个字符时。

#include <stdbool.h>  // for bool, true, false
  

  bool previous_character_was_a_newline = true;
  while ((c = getc(fp)) != EOF) { 
     if (previous_character_was_a_newline) {
          previous_character_was_a_newline = false;
          printf("%d ", n);
     }
     putc(c, stdout); 
     if (c == '\n') {
        n++;
        previous_character_was_a_newline = true;
     }
  }

不要写n++, printf("%d ", n);之类的代码,会比较混乱。非常喜欢:

     if (c == '\n') {
        n++;
        printf("%d ", n);
     }

【讨论】:

    【解决方案2】:

    您的实现输出第一行之前和每个换行符之后的行号,包括文件末尾的行号。这会导致文件末尾出现额外的行号。

    让我们更精确地定义输出:

    • 你想要每行开头的行号,如果没有行则不输出,最后一行之后没有行号。
    • 您是否希望在读取新文件时将行计数器重置为1?我认为不会,但 cat -n 会。
    • 是否要在不以换行符结尾的非空文件末尾输出一个额外的换行符?我认为是,但 cat -n 不是。

    这是一个修改后的版本,第一个问题的答案是 no,第二个问题的答案是 yes

    #include <stdio.h>
    
    int output_file(FILE *fp, int line) {
        int c, last = '\n';
        while ((c = getc(fp)) != EOF) {
            if (last == '\n') {
                printf("%d\t", line++);
            }
            putchar(c);
            last = c;
        }
        /* output newline at end of file if non empty and no trailing newline */
        if (last != '\n') {
            putchar('\n');
        }
        return line;
    }
    
    int main(int argc, char *argv[]) {
        int n = 1;
    
        if (argc < 2) {
            n = output_file(stdin, n);
        } else {
            for (int i = 1; i < argc; i++) {
                FILE *fp = fopen(argv[i], "r");
                if (fp == NULL) {
                    perror(argv[i]);
                } else {
                    n = output_file(fp, n);
                    fclose(fp);
                }
            }
        }
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-11-04
      • 1970-01-01
      • 2017-08-29
      • 2022-12-13
      • 1970-01-01
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多