tags:

views:

115

answers:

4

Hi, Consider i have a file, 'emp.txt' whose content is,

EmpNo.   Name   Phone No.  Salary

1         ABC    123        321

2         CBA    456        543

Now i want to change the phone no. 1st Employee alone. When i tried using ios:ate, all the contents of the file got deleted and the new phone no. got inserted. How can i solve this?

+2  A: 

If you open a file for just output, the library usually truncates the existing file. To change the existing contents of a file, the easiest way is to open it in 'read/write' mode so that you can seek to the correct position and partially overwrite its contents.

Try something like:

std::fstream filestream( "emp.txt", std::ios_base::in | std::ios_base::out );

or if you're using C streams:

FILE* f = fopen( "emp.txt", "r+" );
Charles Bailey
+1  A: 

Change mode of Stream opening

See all possible Modes here

sat
A: 

For your example I think it would better just is to load the whole file, do your change and then write back the whole file. If the file is large then not.

Anders K.
A: 

In Windows, MapViewOfFile() works great in the special case where you are just overwriting digits in-place and the tail of the file need not move. If you DO need to rewrite the entire file, there's a Wikipedia entry on "Transactional NTFS" for ultimate peace-of-mind.
Memory-mapped-files in my experience work REALLY well. If your process crashes, typically the very last byte you happened to write will still be flushed to disk correctly, since Windows robustly knows which pages are dirty.
Which SUGGESTS "padding your records" so that even typical Address-changes might be accomplished without moving the tail of the file.

pngaz