Solved

fstream read and write problem

Posted on 2007-04-07
7
1,238 Views
Last Modified: 2008-01-09
i want to write read/write both using fstream, no ifstream/ofstream. here is what i'm trying
string s;
fstream file("test.txt");
file>>s;
cout<<s; //to console
file<<s;
file.flush();
file.close();

it is reading from file, but not writing, can u fix my problem here?
0
Comment
Question by:marchent
7 Comments
 
LVL 1

Assisted Solution

by:robear7nt
robear7nt earned 100 total points
ID: 18869083
you need to close and then reopen the file to be able change from reading to writing, or writing to reading.

Here is short example:

#include <fstream.h>

int main(int argc, char* argv[])
{
  fstream file;

  file.open("C:\\Test\\Test File 1.txt", ios::out);
  file << "data";
  file.close();

  file.open("C:\\Test\\Test File 1.txt", ios::in);
  char s[5];
  file >> s;
  file.close();

  cout << s;
  return 0;
}
0
 
LVL 13

Author Comment

by:marchent
ID: 18869111
not this one, ur using open() second time, and i don't know the file name that time, caus i'm calling in and out into different diffferent function.
0
 
LVL 1

Expert Comment

by:robear7nt
ID: 18869141
Your last comment does not match your "here is what I'm trying" from original question.

Can you please post EXACTLY what you are trying to do, please :)
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 1

Expert Comment

by:robear7nt
ID: 18869203
I think this what you are looking for, reading and writing file with only one open. Notice the file is opened specifing both input and output.


#include <fstream.h>

int main(int argc, char* argv[])
{
   char s[2046];
   fstream file;

   file.open("C:\\Test\\Test File 1.txt", ios::out | ios::in);

   long beginfile = file.tellp(); // get the beginning of file position
   file << "data\n";              // write some data
   file << "more data";           // write more data
   long endfile = file.tellp();   // get the end of file position
   file.flush();                  // flush the buffer
   file.seekg(beginfile);         // go to beginning of file
   file.get(s, 5);                // read 4 chars and a null into s
   cout << s << endl;             // print it out
   file << s;                     // write those 4 chars after the four we just read
   file.seekg(endfile);           // go to what was the end of file
   file << s;                     // write those 4 chars again
   file.close();                  // close the file

   return 0;
}

The file contents look funky now!
0
 
LVL 1

Expert Comment

by:robear7nt
ID: 18869302
I think my above example has an error in it; you should use seekp (not seekg) to move the "put" pointer. seekg changes the "get" pointer. Sorry!
0
 
LVL 17

Accepted Solution

by:
rstaveley earned 300 total points
ID: 18869957
robear7nt's explanation is spot on, but it begs the question why you want a stream which is open for both input and output.

If it is a text file and you have variable length lines of text, overwriting is tricky business. It is much easier to open the file for reading only and create another new file for writing,  copy lines you want to leave intact and replace those you want to replace. Then delete the original (or make it backup) and rename the new one. You are in better shape for dealing with having your process killed, if you don't leave streams open.

File too large for this approach? Howabout a database?

If it is a binary file, I can see the value of ios::out | ios::in, but do consider flushing buffers, if you are going to leave the iostream open.
0
 
LVL 4

Assisted Solution

by:MacroLand
MacroLand earned 100 total points
ID: 18870289
This was my post to an earlier question;

struct INFORMATIONSTRUCT
      {
            string name;
            string surname;
            int age;
      }info;

      info.name="Name";
      info.surname="Surname";
      info.age=30;

     

      fstream fs("C:\\myfile.txt",ios::out);
      fs.write(reinterpret_cast<char*>(&info),sizeof(info));
      fs.close();

      INFORMATIONSTRUCT s;
      fstream cs("C:\\myfile.txt",ios::in);
        cs.read(reinterpret_cast<char*>(&s),sizeof(s));
        cs.close();

      cout<<s.age<<endl;

Regards,
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now