如何在CSV文件的顶部插入数据? [英] How do I insert data at the top of a CSV file?

查看:60
本文介绍了如何在CSV文件的顶部插入数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何返回csv文件的开头并添加行?

How can I go back to the very beginning of a csv file and add rows?

(我正在使用fprintf()从C打印到CSV文件.在打印数千行(5列)数据的最后,我想回到文件顶部并插入一些动态标头数据(基于事物打印所有内容的方式.)

(I'm printing to a CSV file from C using fprintf(). At the end of printing thousands of rows (5 columns) of data, I would like to go back to the top of the file and insert some dynamic header data (based on how things went printing everything). )

谢谢.

推荐答案

由于文件的结构方式,这或多或少是不可能的.为了完成您想要的:

Due to the way files are structured, this is more or less impossible. In order to accomplish what you want:

  1. 将csv数据写入file1
  2. 将标头写入file2
  3. 将文件1的内容复制到文件2
  4. 删除文件1

或者您可以在完成处理并了解标头之后,将CSV数据保存在ram中并将其写入文件.

Or you can hold the csv data in ram and write it to file after you're finished processing and know the header.

另一种选择是为标头留出一定数量的字节,这对于大型文件而言将以最小的空间成本更快地工作.由于空间是在写入开始时在文件中分配的,因此没有任何问题可以回去填充.请以随机访问("r +")的方式重新打开文件,默认情况下它指向文件的顶部,写入标题并关闭.

Another option is to set aside a certain number of bytes for the header, which will work much faster for large files at minimal space cost. Since the space is allocated in the file at the start of the write, there aren't any issues going back and filling it in. Reopen the file as random access ("r+"), which points to the top of the file by default, write header, and close.

这篇关于如何在CSV文件的顶部插入数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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