问题描述
我在程序中生成了大约2000行文本的文件,每一行都包含员工的信息,并且输出如下所示
I have a file of about 2000 lines of text that i generate in my program, every line has the information of an employee and it's outputed like this
但是,每当我编辑员工信息时,我都必须更新文件,这是我在搜索该行并尝试将其重写
But i whenever i edit an employee information i have to update the file, what i'm doing it's i search for the line and try to rewrite it
我已经看到以下有人遇到相同问题的问题,但是当我尝试写入文件时,它总是写入文件末尾
I've seen the following question of someone with the same problem, but when i try to write to the file it always writes to the end of file
这是我的代码:
datos = fopen(archivo,"a+");
for(i=0;i<num;i++){
// buscar la linea
fgets(lineaA,100,datos);
// sobreescribir
if(i == (num-1))
cursor = ftell(datos);
}
cursor -= strlen(lineaA) - 1;
fseek(datos,cursor,SEEK_CUR);
fputs(linea2,datos);
fclose(datos);
推荐答案
您几乎无法做到这一点.
You pretty much can't do this.
您可以使用fseek
转到文件中的特定位置,并且可以将数据写入该位置(您可能希望使用"r+"
模式).
You can use fseek
to go to a specific location in a file, and you can write data to that location (you probably want to use "r+"
mode).
但是文件通常以字节(或字符)序列而不是行序列存储.
But a file is typically stored as a sequence of bytes (or characters), not as a sequence of lines.
如果您要小心地写出与行中完全相同的字节数,则可以避免使用它-但是在您的示例中,行的长度是不同的,所以这不是一个选项.
If you're careful to write exactly the same number of bytes that were already in the line, you can probably get away with it -- but in your example, the lines are of varying lengths, so this isn't an option.
例如,您可以在每行上填充空格,以便它们都具有相同的长度,但是如果您使用普通的文本编辑器修改文件,则很容易破坏布局.
You could, for example, pad each line with blanks, so they're all the same length, but then it's easy to corrupt the layout if you modify the file using, say, an ordinary text editor.
对于文本文件,通常的方法是将文件读入内存,修改内存中的表示形式,然后重新创建整个文件.您可能想要将内容写入新的临时文件,然后在确认没有写入错误后将其重命名.
For text files, the usual approach is to read the file into memory, modify the in-memory representation, and then re-create the entire file. You probably want to write the contents to a new temporary file, then rename it after you've confirmed that there were no write errors.
这是文本编辑器通常要做的.
This is what text editors typically do.
(不必太担心效率; 2000行并不算太大,而且您不会注意到编写它们所花费的时间.)
(Don't worry too much about efficiency; 2000 lines isn't all that big, and you won't notice the time it takes to write them.)
还有其他选择.您可以定义具有固定长度记录的二进制格式,也可以使用数据库.或者,您可以仅在文件中添加新行,然后将重复的视为已被删除(但这会导致文件很大,如果您进行大量更新的话).
There are alternatives. You can define a binary format with fixed-length records, or you can use a database. Or you can just append new lines to the file, and treat duplicates as if they had been deleted (but this can cause the file to grow very large if you do a lot of updates).
这篇关于覆盖c中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!