I am trying to figure out how to write a new line of text at the beginning of a file (a header). I know I can open the file, or seek to the beginning of a file, but if I write with that, it will overwrite what's there. Do I have to write a new file and then write the other data to it line by line, or is there a better way?
我试图弄清楚如何在文件的开头(标题)写一个新的文本行。我知道我可以打开文件,或者寻找文件的开头,但如果我用它写,它会覆盖那里的内容。我是否必须写一个新文件,然后逐行写入其他数据,或者有更好的方法吗?
Example file:
1, 01/01/09, somedata, foo, bar
2, 01/02/09, somedata, foo, bar
3, 01/03/09, somedata, foo, bar
And I want to end up with
我想结束
3, 1-3, 01/04/09
1, 01/01/09, somedata, foo, bar
2, 01/02/09, somedata, foo, bar
3, 01/03/09, somedata, foo, bar
EDIT:
This is what I ended up doing:
这就是我最终做的事情:
FILE *source;
FILE *output;
char buffer[4096];
size_t bytesRead;
memset(buffer, 0, sizeof(buffer);
source = fopen("sourcefile.txt", "r");
output = fopen("output.txt", "w+");
fprintf(output, "my header text\n");
while(!feof(source))
{
bytesRead = fread(&buffer, 1, sizeof(buffer), source);
fwrite(&buffer, 1, bytesRead, output);
}
fprintf(output, "my footer text");
fclose(source);
fclose(output);
remove(source);
rename("output.txt", "source.txt");
3 个解决方案
#1
You will have to rewrite the whole file, but that doesn't necessarily mean you have to read and write the original data line-by-line. Reading by lines is relatively slow, so if the file is small enough to fit in memory, read it all in one big chunk (or in large sized blocks) and then write it back after writing your new data.
您将不得不重写整个文件,但这并不一定意味着您必须逐行读取和写入原始数据。按行读取相对较慢,因此如果文件足够小以适合内存,请在一个大块(或大型块)中读取它,然后在写入新数据后将其写回。
#2
Well, probably the very easiest thing is to notice that what you want to do is the equivalent of the unix cat
command. If you're on unix, you could just call it from within c. Or you could read the source in gnu textutils.
好吧,可能最简单的事情是注意你想要做的是相当于unix cat命令。如果您使用的是unix,则可以从c中调用它。或者你可以在gnu textutils中阅读源代码。
But in any case all of these solutions do just rewrite the file!
但无论如何,所有这些解决方案都只是重写文件!
#3
You have to open a new file and write all over again.
您必须打开一个新文件并重新编写。
#1
You will have to rewrite the whole file, but that doesn't necessarily mean you have to read and write the original data line-by-line. Reading by lines is relatively slow, so if the file is small enough to fit in memory, read it all in one big chunk (or in large sized blocks) and then write it back after writing your new data.
您将不得不重写整个文件,但这并不一定意味着您必须逐行读取和写入原始数据。按行读取相对较慢,因此如果文件足够小以适合内存,请在一个大块(或大型块)中读取它,然后在写入新数据后将其写回。
#2
Well, probably the very easiest thing is to notice that what you want to do is the equivalent of the unix cat
command. If you're on unix, you could just call it from within c. Or you could read the source in gnu textutils.
好吧,可能最简单的事情是注意你想要做的是相当于unix cat命令。如果您使用的是unix,则可以从c中调用它。或者你可以在gnu textutils中阅读源代码。
But in any case all of these solutions do just rewrite the file!
但无论如何,所有这些解决方案都只是重写文件!
#3
You have to open a new file and write all over again.
您必须打开一个新文件并重新编写。