Solved

fstream read and write problem

Posted on 2007-04-07
7
1,262 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
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

770 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