首页 > 解决方案 > 在C文件的开头插入文件中的行数的最佳方法是什么?

问题描述

我有一个文件,其中几行被转储。我想后期处理该文件并在该文件的开头插入一个标题。标题基本上是插入标题之前文件中的行数。无论平台如何,我都需要用 C 语言编写它。我正在考虑在 C 代码中使用系统命令来计算文件中的行数:

int header = system("wc -l myfile");

将标题保存在临时文件中;将 myfile 附加到临时文件中;用 myfile 替换或移动 tempfile

寻找更好的方法。

标签: clinuxunix

解决方案


使用diffhttps://unix.stackexchange.com/questions/252927/what-do-the-numbers-in-the-line-mean-in-output-of-diff)然后你知道哪些行被转储了

要将文本写入文件的开头,请使用 shell 命令,例如sed -i '1s/^/task goes here\n/' todo.txthttps://superuser.com/questions/246837/how-do-i-add-text-to-the-beginning-of-a-file-in- bash ),在 C 中,您可以使用shsystem依赖于 shell 命令是否是内置的来执行 shell 命令。

如果您希望这个平台独立,您必须像https://www.geeksforgeeks.org/c-program-count-number-lines-file/一样计算 C 中的行数


推荐阅读