Thread: read and write to file

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    58

    read and write to file

    hi, i was trying to write data to the end of a data file. i first read till the end of file and THEN tried write to the file. it compiles while,reads well..but wont write the data

    this is my code
    Code:
    #include <iostream>
    #include <string>
    #include <fstream>
    using namespace std;
    int main(void){
    	fstream myfile ("a.dat");
    	string line;
    	//read and go to end of file
    	while (! myfile.eof() ){
    		getline(myfile,line);
    		cout<<line<<endl;
    	}
    	/*write to file*/
    	char *line1="testing line1";	
    	char *line2="testing line2";
    	myfile.write(line1,15);
    	myfile.write(line2,15);
    }
    hope some 1 can correct my error. thanx

  2. #2
    Registered User
    Join Date
    May 2006
    Posts
    903
    Don't use pointer to characters, use std::string s.

    Code:
    std::string line1 = "testing line 1";
    myfile << line1;

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    also don't use eof to control a loop - check the return value of getline instead (see FAQ on File IO)

    Also you need to clear the fail state before writing...
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  2. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  3. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  4. SYnchronize read & write of a cache file
    By lei_michelle in forum C Programming
    Replies: 4
    Last Post: 02-26-2008, 05:49 PM
  5. Replies: 3
    Last Post: 03-04-2005, 02:46 PM