How do I go back to end of the first line in csv file?
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 开发者_StackOverflow社区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.
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:
std::ostringstream label;
label << "Shape";
std::ostringstream area;
area << "Area";
std::ostringstream min;
min << "Min";
std::ostringstream max;
max << "Max";
for (std::vector<Shape>::const_iterator> it = shapes.begin();
it != shapese.end();
++ it)
{
label << ',' << it->TypeName();
area << ',' << it->Area();
min << ',' << it->min();
max << ',' << it->max();
}
dest << label.str() << '\n';
dest << area.str() << '\n';
dest << min.str() << '\n';
dest << max.str() << '\n';
You can use the old FILE*
API, seek
ing as needed. IOStreams also allow you to seekp
and seekg
. 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.
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
精彩评论