Solved

fstream read and write problem

Posted on 2007-04-07
7
1,277 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
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…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

679 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