prePEND文本在C文件 [英] Prepend text to a file in C

查看:139
本文介绍了prePEND文本在C文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用C,这些文件可能会相当大一个标准的头添加到一个文件(或文件组),所以这将是一个坏主意,它们加载到内存中,或将它们复制到临时文件(我想)。

有没有简单地prePEND直接头到每一个文件的方式?

头本身是相当小的,不超过1 KB


解决方案

应该可以不用临时文件 - 你可以阅读从最终的文件,逐块,在写每个块回(original_position + header_size)。第一块将被写回 header_size ,留有余地头。

不过,你真的不希望这样做。这将损坏的文件,如果中止(想:磁盘空间,其他I / O错误,掉电,等等)。

因此​​,你实际上应该使用临时文件 - 写它你需要的一切,然后将其重命名为原来的文件名(假设你创建相同的文件系统上的临时文件,否则你需要复制)

编辑:澄清我的意思,简化的解决方案时,整个文件在RAM适合:


  • 分配缓冲区大小相同的文件

  • 打开文件,并读入缓冲区

  • 求(文件,header_size),并写在这里的缓冲

  • 求(文件,0)写的标题

如果该文件是为大,你可以分配较小的缓冲区,并重复读/写在开始读FILE_SIZE - BUFFER_SIZE FILE_SIZE写 - BUFFER_SIZE + header_size 。 2 * BUFFER_SIZE ,写在 FILE_SIZE - - 2 * BUFFER_SIZE + header_size ,然后在读下一大块FILE_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!

这篇关于prePEND文本在C文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆