简体   繁体   English

在 C 中的文件中添加行号

[英]Adding line numbers in a file in C

I am trying to master working with files in C, and I have a bump which I can't pass.我正在尝试使用 C 语言处理文件,但我有一个无法通过的颠簸。 I have been searching all day for information but I can't seem to find what I am looking for.我一整天都在寻找信息,但似乎找不到我要找的东西。 I would like to number the lines in a file.我想对文件中的行进行编号。 For example, if I type in information about a book (let's say: Name, Air-date and id), I would expect something like this in my file:例如,如果我输入关于一本书的信息(比方说:姓名、播出日期和 ID),我希望我的文件中有这样的内容:

1. Name:Dave Air-Date:1997 id:123

And I would like this to update itself.我希望它能够自我更新。 Say I close the program and run it again, the counting should start from 2.假设我关闭程序并再次运行它,计数应该从 2 开始。

My only problem is numbering the lines.我唯一的问题是给行编号。 Could someone point me in the right direction how to do this, or show me a sample source code?有人可以指出我如何做到这一点的正确方向,或者向我展示示例源代码吗?

You could process each character one by one, and increment a counter that you print before the character when you encounter a carriage return ( \\n ).您可以一个一个地处理每个字符,并在遇到回车符 ( \\n ) 时增加在字符之前打印的计数器。

In pseudo-code:在伪代码中:

lineNumber = 1;
Open the file
While ((c = read a character) is not EOF)
    If (c is \n)
        Print "lineNumber", then increment it
    Print c
End while
Close the file

It's too late, but I hope it helps.为时已晚,但我希望它有所帮助。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
  /* user input */
  char text[50];
  char res[100] = "";
  printf("Enter a short story (<100 characters): ");
  char ch;
  char *ptr = text;
  while ((ch = getchar()) != EOF) {
    *ptr++ = ch;
  }
  printf("\nYou've entered this text:\n");
  printf("%s\n", text);

  /* append and create a new text */
  strcat(res, "0: ");
  char *qtr = text;
  int i = 1;
  while (*qtr != '\0') {
    if (*qtr != '\n') {
      char temp[2];
      sprintf(temp, "%c", *qtr);
      strcat(res, temp);
    } else {
      char temp[5];
      sprintf(temp, "\n%d: ", i++);
      strcat(res, temp);
    }
    qtr++;
  }

  printf("\nLine number added: \n");
  printf("%s\n", res);

  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM