C - 如何在不篡改输出文本中现有行的情况下编写新行?

标签 c text newline

我有这个代码

<....
 Gets input from input.txt, which contains several lines
 the code checks each lines, determining the usefulness by calculating BR and BL, 
 the 2 INT variables to detect whether the text is useful or not
 ....>

 if (BR > BL)

 //if the BR in a line is greater than the BL, I want to copy that line (from input.txt)
 //and paste it to output.txt. 
 //So then the output.txt will only contains lines that has BR > BL 

 {
    wr_file=fopen("output.txt", "w");
    fprintf (wr_file, "%s \n", text);
 }

程序可以正确检测出每一行的BR和BL。但是使用最后一个代码,我似乎无法正确地将有用的行从 input.txt 复制到 output.txt

假设这是我的 input.txt :

1. carrot cabbage tomato
2. potato rice
3. cabbage eggplant

据说第一行和第三行是有用的。所以output.txt应该是这样的:

1. carrot cabbage tomato
3. cabbage eggplant

但它看起来像这样:

3. cabbage eggplantomato

正如你所看到的,它确实复制了第一行,但是当它必须写入第三行时,它并没有将其写入新行,而是篡改了第一行。

请帮忙,我怎样才能正确复制这些行。

最佳答案

没有 MCVE ,不可能正确调试,但我认为,你的问题是,你正在调用

wr_file=fopen("output.txt", "w");

多次,这就是您的输出被覆盖并且仅保留最后一次写入的原因。 fopen() 目标文件仅一次,并保持 fwrite() 循环。

此外,在使用时,您需要 NULL NUL 终止输入文件中的输入 [text]作为字符串 [例如:传递给fwrite()]。

关于C - 如何在不篡改输出文本中现有行的情况下编写新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26883799/

相关文章:

c - 修改用户输入文件路径以扫描C中同一目录中的文件

c++ - 如何在 makefile 指令中包含 C 和 C++ 文件

c - 通过地址(指针)传递

android - 如何在 Jetpack Compose 中使文本可滚动

C# 控制台 - 如何在没有新行的情况下读取 ReadLine()? (或撤消 a\n 或垂直\b)

php - 如何从 php 字符串中删除新行和返回?

c++ - 如何将 printf 流输出重定向到 .csv 文件?

jquery - (event.target).text() 返回 url 而不是文本

python - BeautifulSoup 返回意外的额外空间

windows - 使用 Windows 批处理文件在文本文件中添加新行