如何返回 csv 文件中第一行的末尾?
我正在使用 ofstream 编写 csv 文件。 目前,我正在使用“<<”从左到右书写它。运算符,这很容易。 例如,
Shape,Area,Min,Max
Square,10,2,11
Rectangle,20,3,12
我想进行更改,以便看起来
Shape,Square,Rectangle
Area,10,20
Min,2,3
Max,11,12
我知道我可以使用“<<”运算符,就这样写,但我正在使用一些循环,并且不可能使用“<<”操作员这样写。
所以我正在寻找一种按顺序编写的方法,例如
Shape,
Area,
Min,
Max,
“Then”变成
Shape,Square
Area,10
Min,2
Max,1
“So”,它基本上是从上到下而不是从左到右。 我如何使用 ofstream 来编写此代码?我猜我必须使用eekp,但我不知道如何使用。 非常感谢。
I am using ofstream to write a csv file.
Currently, I am writing it left to right using "<<" operator, which is easy.
For example,
Shape,Area,Min,Max
Square,10,2,11
Rectangle,20,3,12
I want to change so that it looks like
Shape,Square,Rectangle
Area,10,20
Min,2,3
Max,11,12
I know I can use "<<" operator and just write it that way, but I am using some loops and it's not possible to use "<<" operator write it like that.
So I am looking for a way to write in the order, for example
Shape,
Area,
Min,
Max,
Then becomes
Shape,Square
Area,10
Min,2
Max,1
So It's basically going from top to bottom rather than left to right.
How do I use ofstream to code this? I am guessing I have to use seekp, but I'm not sure how.
Thank you very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除非在 ostream 的末尾,否则您不能插入其他内容
覆盖已经写入的数据。对于类似什么的事情
你想要做的,你可能必须收集每一行
单独的字符串(也许使用 ostringstream 来编写它),然后
输出行。像这样的东西:
You can't insert other than at the end of an ostream without
overwriting already written data. For something like what
you're trying to do, you probably have to collect each row in
separate string (perhaps using ostringstream to write it), then
output the rows. Something like:
您可以使用旧的
FILE*
API,根据需要seek
。 IOStreams 还允许您seekp
和seekg
。但像这样操作文件会很困难。如果您在开头写出 100 个字节seekp
并开始写入更多数据,您将覆盖已经存在的内容(它不会自动为您移动)。您可能需要读取文件的内容,在内存中操作它们,然后一次性将它们写入磁盘。You can use the old
FILE*
API,seek
ing as needed. IOStreams also allow you toseekp
andseekg
. But manipulating files like this will be difficult. If you write out, say, 100 bytes,seekp
to the beginning and start writing more data, you're going to overwrite what's already there (it doesn't automatically get shifted around for you). You're likely going to need to read in the file's contents, manipulate them in memory, and write them to disk in one shot.尽管效率很低,但可以通过编写固定大小的行(40个字符?)和额外的空格来完成,因此您可以通过查找行* 40 +位置(或查找逗号)来转到行和(固定)位置覆盖空格。
现在您已经掌握了这些知识,请采用 Martin 提到的方法
Eventhough it is inefficient, it could be done by writing fixed size lines (40 characters?) with extra spaces, so you can go to a line and (fixed) position by seeking line*40+position (or look for the comma) and overwrite the spaces.
Now that you have this knowledge, go for the approach as mentioned by Martin