CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Mar 2009
    Posts
    29

    Text File Input and Output at the same time

    Good day!

    I am trying to do basic text file input/output and i have stumbled on this problem:
    When using the code beneath, nothing is written in the txt file.
    If i omit the while block then "Testing..." is correctly written within the txt file.
    So my guess is i cannot write in a file while i am reading it, but isn't that the point of fstream?
    Any ideas? How can i overcome this problem?

    std::fstream openfile;

    openfile.open ("open.txt",std::ios::app);
    char linefile[256];
    while (openfile) {
    openfile.getline(linefile,256);
    openfile << "Some Text\n";

    }
    openfile << "Testing...\n";
    openfile.close();

    Thanx in advance,
    Stakon

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: Text File Input and Output at the same time

    1) You do not open the file for reading (missing std::ios::in)

    2) Even if you add that , app | in is not a legal combination
    of open modes. You could use : out | in

    3) Bi-directional streams are tricky ... there are a few rules:

    a) switching from output to input ... must either flush the
    buffer or re-position the stream pointer, or the results are
    un-defined.

    b) switching from input to output ... must reposition the
    stream pointer or the results are undefined. Exception:
    reading to end-of-file, you can write immediately to the
    end (after clearing the stream's state).

  3. #3
    Join Date
    Mar 2009
    Posts
    29

    Re: Text File Input and Output at the same time

    Thanx Philip,

    that pretty much covered what i was missing.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured