c - 在C文件的开头插入文件中的行数的最佳方法是什么?
问题描述
我有一个文件,其中几行被转储。我想后期处理该文件并在该文件的开头插入一个标题。标题基本上是插入标题之前文件中的行数。无论平台如何,我都需要用 C 语言编写它。我正在考虑在 C 代码中使用系统命令来计算文件中的行数:
int header = system("wc -l myfile");
将标题保存在临时文件中;将 myfile 附加到临时文件中;用 myfile 替换或移动 tempfile
寻找更好的方法。
解决方案
使用diff
(https://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.txt
(https://superuser.com/questions/246837/how-do-i-add-text-to-the-beginning-of-a-file-in- bash ),在 C 中,您可以使用sh
或system
依赖于 shell 命令是否是内置的来执行 shell 命令。
如果您希望这个平台独立,您必须像https://www.geeksforgeeks.org/c-program-count-number-lines-file/一样计算 C 中的行数
推荐阅读
- jquery - Jquery - resize() 上的单击事件无法正常工作
- javascript - 如何使用 Node Streams 和 Promise 避免内存泄漏
- dataset - 如何在 colab 中加载巨大的数据集以转换为 spacy JSON?
- c++ - 找不到重复案例时,“案例标签值已出现在此开关中”
- php - 通过php连接到sql server时未建立连接
- javascript - 使用 PrimeNG DynamicDialog 的 mouseenter mouseleave 问题
- qt - 在 Designer / Creator 中管理 QWidgets 的操作列表?
- javascript - 更改显示属性时,有序列表向左移动
- flutter - Flutter:无法使用 GradleUserHomeServices.createResourceSnapshotterCacheService() 创建 ResourceSnapshotterCacheService 类型的服务
- flutter - 如何将 context.read 传递给 Flutter 中的子小部件?潜在的 BuildContext 错误问题