Thread: copying a file, ifstream+ofstream?

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    266

    copying a file, ifstream+ofstream?

    I decided I wanted to learn some file i/o and started by copying a file...specifically an image png file.. which ended up working but am wondering if this is the best/correct way to be doing this and if I could possibly run into problems ?

    I used this code for a simple 2 liner of text file and it worked, then to my surprise it worked on an image without complain though.

    is there a more clever way than this, that i am not seeing?
    Code:
    void copy_file(string srcf , const char *destf)
    {
    	ofstream dest;
    	ifstream src;
    	src.open(srcf.c_str());
    	dest.open(destf);
    	string words;
    	while(getline(src,words))
    	{
    		dest << words << endl;
    	}
    }
    and as well, I read that theres a close method.. are file automatically closed anyway? I mean my file was created .. it must have been closed by itself anyway.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Streams are closed when the variable goes out of scope (i.e., as part of the destructor). On some architectures (e.g. Windows if I recall correctly) some binary files may get mangled by getline (a \r\n pair would get translated into just \n). You can open a file in C++ in binary mode by
    Code:
    src.open(srcf.c_str(), ios::binary);

  3. #3
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    This should work:
    Code:
    dest << src.rdbuf();
    At least... I GUESS it's standard compliant, but someone else should probably tell us whether I'm right.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Copying content of file into a 2D array
    By trueman1991 in forum C Programming
    Replies: 10
    Last Post: 12-16-2009, 12:42 AM
  2. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  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. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM