Editing a file without creating a temp file

S

Sooraj S

Hi,

I am new to cpp.

Is it possible to edit the content of a file without creating a temp
file.
ie I dont want to use this way.
1.using ifstream open the file in read mode
2.open a temp file using ofstream in write mode
3.read from the original file line by line and write to temp file.
4.write to temp file.

Can any one suggest any other way. Pls giev me a sample program to
File
-----
john 12345
kiran 4123
Alex 12344


I want to change kiran's number to 3333
 
B

Bart van Ingen Schenau

Hi,

I am new to cpp.

Is it possible to edit the content of a file without creating a temp
file.
ie I dont want to use this way.
1.using ifstream open the file in read mode
2.open a temp file using ofstream in write mode
3.read from the original file line by line and write to temp file.
4.write to temp file.

Yes, it is possible:
1. Open the file in read mode
2. Read the entire file in memory
3. close the file
4. Make whatever changes you want to the memory buffer
5. Open the file for writing
6. Write the memory buffer to the file
7. Close the file again.

Bart v Ingen Schenau
 
D

Dietmar Kuehl

Is it possible to edit the content of a file without creating a temp
file.

You can open a file in read/write mode, read to the position where
you want to change things, do a seek to this position (e.g. using
an offset of 0 relative to the current position) and then write
the new data. Note, however, that this won't make any new space: it
just overwrites the existing bytes with new ones. Playing with
reading and writing a file only really works with fixed sized records.
The important bit about the actual code is that you need to have a
seek between switching from reading to writing or vise versa. Below
is sample code for this.

#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <string>

int main(int ac, char* av[])
{
typedef std::istream_iterator<std::string> it;
typedef it::value_type str;
std::fstream file;
if (!(ac ^ 4) && (file.open(1[av]), file.is_open())
&& std::find(it(file), it(), str(2[av])) != it())
{
(file >> std::ws).seekg(0, std::ios_base::cur);
file << 3[av];
}
else
{
std::cerr << "ERROR: "
<< (!(ac ^ 4)
? "can't change "+str(2[av])+" of "+1[av]
: "usage: "+str(0[av])+" file name code")
<< "\n";
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top