read and write to file

This is a discussion on read and write to file within the C++ Programming forums, part of the General Programming Boards category; hi, i was trying to write data to the end of a data file. i first read till the end ...

  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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,424
    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...
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

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, 04:49 PM
  5. Replies: 3
    Last Post: 03-04-2005, 01:46 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21