我有这个代码
<....
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/