How to prepend to a file (add at the top)

后端 未结 8 987
逝去的感伤
逝去的感伤 2020-12-20 13:12

Imagine you have a file

sink(\"example.txt\")
data.frame(a = runif(10), b = runif(10), c = runif(10))
sink()

and would want to add some hea

相关标签:
8条回答
  • 2020-12-20 13:39

    Either (A) Read the file in, add your header before and write back out (as Gareth suggested) ..or (B) Cache what you want write to the file somewhere and only write it all out when you've generated your header.

    0 讨论(0)
  • 2020-12-20 13:41

    In C++, if you're willing to get your hands dirty, you can take the following steps.

    1. Stream the new content into temporary buffer (so you know the exact size of the new content)
    2. Resize the file (truncate(), ftruncate()) to include current size plus new size
    3. Map the whole file in
    4. memmove() the original file size to new position which is the new content size
    5. Copy the new data at position 0.

    It's probably less effort to:

    1. Construct a new file and push the new content in
    2. Read the old file and push that in too
    3. Call operating system calls to move the new file to the old file
    0 讨论(0)
提交回复
热议问题