views:

67

answers:

4

Text file (or CSV) is:

Data:,,,,,\n  

(but with 100 ","s)

In C or C++ I would like to open the file and then fill in values between the ",".
i.e.- Data:,1,2,3,4,\n

I'm guessing that I need some sort of search to find the next comma, insert data, find the next comma insert, etc.

I was looking at memchr() for a buffer and was wondering if there is something similar for a text file?

If you could point me in the right direction, I would appreciate it.

(I don't mind reading a book to find something out like this either, I just don't know what book would have this information?)

Thank You.

+4  A: 

You can't actually do that in C... if you open in read/write mode you'll overwrite characters, not insert them.

http://c-faq.com/stdio/fupdate.html

You need to open the file, read the line into memory, write the new line to a temp file.

After you're done inserting all the lines, copy the temp file over the original file. I don't think there's any other way to do it.

wmil
Depending on the size of the file one could just load it entirely into memory and then insert the data when writing back. This would not require a temporary file.
Space_C0wb0y
The other reason a temporary file is used is to ensure that if there's a crash, you don't replace the good old file with a corrupted half-finished new file. That's not really important in this case though, since the old file is just an empty template.
caf
+3  A: 

(This is for the C++ case) Just parse the data into an Linked list with the Objects that hold the data, modify the data and overwrite the file.

You first need to split your data into lines(\n creates a new linked-list Element):

Data:,,,,,\n
Data2:,,,,,\n

will get the strings (pseudolist):

["Data:,,,,,", "Data2:,,,,,"]

So now you need to define your Object for each Line like:

class LineStruct {
   public:
    string head;
    LinkedList<string> data;
};

and fill it.

Then you edit the data-structure and after that you write it back to disk.

Quonux
+2  A: 

If you have

Data:,,,,,\n

then there is no space between the , to fill, you have to write out brand new lines.

However if you had

Data:   ,   ,   ,   ,   ,   \n

then you could overwrite just those parts represented by ' '

in C you would seek to the part of the file and write and then seek to the next pos, sorry no code off the top of my head.

Greg Domjan
+2  A: 

This is where I would look:

As suggested by wmils answer, you will have to either use a temporary file, or hold all the new lines in memory until all lines are processed, and then overwrite the original file.

Space_C0wb0y