Solved

fstream read and write problem

Posted on 2007-04-07
7
1,294 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

 
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: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say 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

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

632 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