将文本添加到 C 中的文件中 [英] Prepend text to a file in C
问题描述
我想使用 C 向文件(或文件组)添加标准头.这些文件可能非常大,因此将它们加载到内存中或将它们复制到临时文件(我想想).
有没有办法简单地将标题直接添加到每个文件中?
标头本身很小,不超过 1 KB
没有临时文件应该是可能的 - 你可以从文件的末尾,一个块一个块地读取文件,将每个块写回 (original_position +header_size)
.第一个块将以 header_size
写回,为标题留出空间.
但是,您并不真的想这样做.如果中止,它会损坏文件(想想:磁盘空间不足、其他 I/O 错误、断电等等).
因此,您实际上应该使用临时文件 - 将您需要的所有内容写入其中,然后将其重命名为原始文件的名称(假设您在同一文件系统上创建临时文件,否则您需要复制).>
澄清我的意思,当整个文件适合RAM时的简化解决方案:
- 分配与文件大小相同的缓冲区
- 打开文件,并将其读入缓冲区
- seek(file, header_size) 并在此处写入缓冲区
- seek(file, 0) 写入头部
如果文件太大,您可以分配较小的缓冲区并重复读取/写入,从 file_size - buffer_size
开始读取,并在 file_size - buffer_size + header_size
写入.然后重复以 file_size - 2 * buffer_size
读取下一个块,以 file_size - 2 * buffer_size + header_size
写入,依此类推.
但让我再说一遍:如果文件失败,您可能会损坏文件!
I want to add a standard header to a file (or group of files) using C. These files could be quite large, so it would be a bad idea to load them into memory, or copy them into temporary files (I think).
Is there a way to simply prepend the header directly to each file?
The header itself is quite small, not more than 1 KB
It should be possible without a temporary file - you can read the file from the end, block by block, writing each block back at (original_position + header_size)
. The first block would be written back at header_size
, leaving room for the header.
However, you don't really want to do this. It would corrupt the file if aborted (think: out of disk space, other I/O error, power down, whatever).
Thus, you should actually use temporary file - write to it everything you need, then rename it to the original file's name (assuming you create temporary file on the same file system, otherwise you'd need to copy).
Edit: to clarify what I mean, simplified solution when the whole file fits in RAM:
- allocate buffer same size as the file
- open the file, and read it into the buffer
- seek(file, header_size) and write the buffer here
- seek(file, 0) write the header
If the file is to big, you can allocate smaller buffer and repeat reads/writes starting with read at file_size - buffer_size
and write at file_size - buffer_size + header_size
. Then repeat with next chunk read at file_size - 2 * buffer_size
, write at file_size - 2 * buffer_size + header_size
, and so on.
But let me repeat: you risk corrupting your file if it fails!
这篇关于将文本添加到 C 中的文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!