Thread: read and write to file

  1. #1
    Registered User
    Join Date
    Feb 2006

    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
    #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() ){
    	/*write to file*/
    	char *line1="testing line1";	
    	char *line2="testing line2";
    hope some 1 can correct my error. thanx

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

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

  3. #3
    "I Win!" by U. Lose vart's Avatar
    Join Date
    Oct 2006
    Rishon LeZion, Israel
    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...
    To be or not to be == true

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