Is this all it takes to copy a file in C++? Is there any error handling
missing in this function?
bool copy_file(std::string first, std::string second)
{
std::ifstream in(first.c_str());
if (!in.is_open())
return false;
std::ofstream out(second.c_str());
if (!out.is_open())
return false;
return out << in.rdbuf();
}
Thanks. 13 2282
Jason Heyes wrote: Is this all it takes to copy a file in C++? Is there any error handling missing in this function?
bool copy_file(std::string first, std::string second)
I'd probably still pass the arguments by ref to const.
{ std::ifstream in(first.c_str()); if (!in.is_open()) return false;
std::ofstream out(second.c_str()); if (!out.is_open()) return false;
return out << in.rdbuf(); }
Seems fine. Of course, returning 'false' gives no idea what has gone
wrong, only that something did go wrong.
V
Victor Bazarov wrote: Jason Heyes wrote: Is this all it takes to copy a file in C++? Is there any error handling missing in this function?
bool copy_file(std::string first, std::string second)
I'd probably still pass the arguments by ref to const.
{ std::ifstream in(first.c_str()); if (!in.is_open()) return false;
std::ofstream out(second.c_str()); if (!out.is_open()) return false;
return out << in.rdbuf(); }
Seems fine. Of course, returning 'false' gives no idea what has gone wrong, only that something did go wrong.
Well, the standard streams don't provide much more anyway, other than
"failed" and "bad".
Rolf Magnus wrote: Victor Bazarov wrote:
Jason Heyes wrote:
Is this all it takes to copy a file in C++? Is there any error handling missing in this function?
bool copy_file(std::string first, std::string second)
I'd probably still pass the arguments by ref to const.
{ std::ifstream in(first.c_str()); if (!in.is_open()) return false;
std::ofstream out(second.c_str()); if (!out.is_open()) return false;
return out << in.rdbuf(); }
Seems fine. Of course, returning 'false' gives no idea what has gone wrong, only that something did go wrong.
Well, the standard streams don't provide much more anyway, other than "failed" and "bad".
Yeah, but with failed and bad, you know what stream failed. With the
OP's code, you don't know whether you couldn't open the source or the
target stream.
red floyd wrote: Jason Heyes wrote:
I'd probably still pass the arguments by ref to const.
{ std::ifstream in(first.c_str()); if (!in.is_open()) return false;
std::ofstream out(second.c_str()); if (!out.is_open()) return false;
return out << in.rdbuf(); }
Yeah, but with failed and bad, you know what stream failed. With the OP's code, you don't know whether you couldn't open the source or the target stream.
Assuming we don't use exceptions, but are using return codes for success:
// assume necessary #includes
int myfunc(const std::string& first, const std::string& second)
{
std::ifstream in(first.c_str());
if (!in.is_open())
return 1;
std::ofstream out(second.c_str());
if (!out.is_open())
return 2;
return (out << in.rdbuf()) ? 0 : 3;
}
Then 0 is success, or the non-zero tells exactly where the error was
(though not *what* it was)
red floyd wrote: Assuming we don't use exceptions, but are using return codes for success:
// assume necessary #includes int myfunc(const std::string& first, const std::string& second) { std::ifstream in(first.c_str()); if (!in.is_open()) return 1;
std::ofstream out(second.c_str()); if (!out.is_open()) return 2;
return (out << in.rdbuf()) ? 0 : 3; }
Then 0 is success, or the non-zero tells exactly where the error was (though not *what* it was)
Instead of int and magic numbers, I'd use something like:
enum IOError
{
NoError,
CantOpenInput,
CantOpenOutput,
CantRead,
CantWrite
//... maybe other possible errors
};
Victor Bazarov wrote: Jason Heyes wrote: return out << in.rdbuf(); }
Seems fine. Of course, returning 'false' gives no idea what has gone wrong, only that something did go wrong.
Does 'return out << in.rdbuf();' report a read error at all??
Panjandrum wrote: Victor Bazarov wrote:
Jason Heyes wrote:
return out << in.rdbuf(); }
Seems fine. Of course, returning 'false' gives no idea what has gone wrong, only that something did go wrong.
Does 'return out << in.rdbuf();' report a read error at all??
Yes. 'out << in.rdbuf()' will fail if extraction can't happen. That will
set the 'failbit' in 'out', which will cause the operator to return the
object with 'failbit' set, which when converted to 'bool' (through void*)
will give 'false'. IIRC that's the standard sequence of things happening.
V
"Panjandrum" <pa********@spambob.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com... Victor Bazarov wrote: Jason Heyes wrote: > return out << in.rdbuf(); > }
Seems fine. Of course, returning 'false' gives no idea what has gone wrong, only that something did go wrong.
Does 'return out << in.rdbuf();' report a read error at all??
Come to think of it, no. When a read error occurs, the function treats it as
eof and stops. This is at least what I think it does. To report all errors I
would do this:
char c;
while (in.get(c))
out.put(c);
return in.eof() && out.good();
"Victor Bazarov" <v.********@comAcast.net> wrote in message
news:oK****************@newsread1.mlpsca01.us.to.v erio.net... Panjandrum wrote: Does 'return out << in.rdbuf();' report a read error at all??
Yes. 'out << in.rdbuf()' will fail if extraction can't happen. That will set the 'failbit' in 'out', which will cause the operator to return the object with 'failbit' set, which when converted to 'bool' (through void*) will give 'false'. IIRC that's the standard sequence of things happening.
Oops. This contradicts what I just wrote. :P
Jason Heyes wrote: "Victor Bazarov" <v.********@comAcast.net> wrote in message news:oK****************@newsread1.mlpsca01.us.to.v erio.net...
Panjandrum wrote:
Does 'return out << in.rdbuf();' report a read error at all??
Yes. 'out << in.rdbuf()' will fail if extraction can't happen. That will set the 'failbit' in 'out', which will cause the operator to return the object with 'failbit' set, which when converted to 'bool' (through void*) will give 'false'. IIRC that's the standard sequence of things happening.
Oops. This contradicts what I just wrote. :P
Eh... I may not be entirely correct there either. Read 27.6.2.5.3 for me,
will you? It says (and I quote):
~~~~~
basic_ostream<charT,traits>& operator<<
(basic_streambuf<charT,traits>* sb);
6 Effects: If sb is null calls setstate(badbit) (which may throw
ios_base::failure).
7 Gets characters from sb and inserts them in *this. Characters are
read from sb and inserted until any of the following occurs:
— end-of-file occurs on the input sequence;
— inserting in the output sequence fails (in which case the character
to be inserted is not extracted);
— an exception occurs while getting a character from sb.
8 If the function inserts no characters, it calls setstate(failbit)
(which may throw ios_base::failure (27.4.4.3)). If an exception was
thrown while extracting a character, the function set failbit in
error state, and if failbit is on in exceptions() the caught
exception is rethrown.
9 Returns: *this.
~~~~~
Now, I think what I said about failing to read falls under the last bullet
item in paragraph 7. But if no exception is thrown, and the buffer goes
bad after reading and inserting several characters, the operation will be
flagged as successful, I guess.
That's where I'm wrong, probably. You still need to test 'in' when
returning the flag. Or not. Depending on what you consider a failure.
V
"Victor Bazarov" <v.********@comAcast.net> wrote in message
news:ur*****************@newsread1.mlpsca01.us.to. verio.net... Jason Heyes wrote: "Victor Bazarov" <v.********@comAcast.net> wrote in message news:oK****************@newsread1.mlpsca01.us.to.v erio.net...
Panjandrum wrote:
Does 'return out << in.rdbuf();' report a read error at all??
Yes. 'out << in.rdbuf()' will fail if extraction can't happen. That will set the 'failbit' in 'out', which will cause the operator to return the object with 'failbit' set, which when converted to 'bool' (through void*) will give 'false'. IIRC that's the standard sequence of things happening.
Oops. This contradicts what I just wrote. :P
Eh... I may not be entirely correct there either. Read 27.6.2.5.3 for me, will you? It says (and I quote): ~~~~~ basic_ostream<charT,traits>& operator<< (basic_streambuf<charT,traits>* sb);
6 Effects: If sb is null calls setstate(badbit) (which may throw ios_base::failure).
7 Gets characters from sb and inserts them in *this. Characters are read from sb and inserted until any of the following occurs: — end-of-file occurs on the input sequence; — inserting in the output sequence fails (in which case the character to be inserted is not extracted); — an exception occurs while getting a character from sb.
8 If the function inserts no characters, it calls setstate(failbit) (which may throw ios_base::failure (27.4.4.3)). If an exception was thrown while extracting a character, the function set failbit in error state, and if failbit is on in exceptions() the caught exception is rethrown.
9 Returns: *this. ~~~~~
Now, I think what I said about failing to read falls under the last bullet item in paragraph 7. But if no exception is thrown, and the buffer goes bad after reading and inserting several characters, the operation will be flagged as successful, I guess.
That's where I'm wrong, probably. You still need to test 'in' when returning the flag. Or not. Depending on what you consider a failure.
Also read paragraph 8. It says that if an exception is thrown while
extracting a character, the function sets failbit in error state. Since a
buffer only goes bad by throwing an exception, the function sets failbit on
a bad read. It looks like you were right.
Since 'out << in.rdbuf()' fails on all errors, we need not test 'in'.
Jason Heyes wrote: "Victor Bazarov" <v.********@comAcast.net> wrote in message news:ur*****************@newsread1.mlpsca01.us.to. verio.net... [...] 8 If the function inserts no characters, it calls setstate(failbit) (which may throw ios_base::failure (27.4.4.3)). If an exception was thrown while extracting a character, the function set failbit in error state, and if failbit is on in exceptions() the caught exception is rethrown.
9 Returns: *this. ~~~~~
Now, I think what I said about failing to read falls under the last bullet item in paragraph 7. But if no exception is thrown, and the buffer goes bad after reading and inserting several characters, the operation will be flagged as successful, I guess.
That's where I'm wrong, probably. You still need to test 'in' when returning the flag. Or not. Depending on what you consider a failure.
Also read paragraph 8. It says that if an exception is thrown while extracting a character, the function sets failbit in error state. Since a buffer only goes bad by throwing an exception,
Is that guaranteed? I didn't see it. Where is it defined?
the function sets failbit on a bad read. It looks like you were right.
Since 'out << in.rdbuf()' fails on all errors, we need not test 'in'.
I'll take your word for it, if you substantiate it with a quote from the
Standard :-)
V
"Victor Bazarov" <v.********@comAcast.net> wrote in message
news:ka*****************@newsread1.mlpsca01.us.to. verio.net... Jason Heyes wrote: "Victor Bazarov" <v.********@comAcast.net> wrote in message news:ur*****************@newsread1.mlpsca01.us.to. verio.net... [...] 8 If the function inserts no characters, it calls setstate(failbit) (which may throw ios_base::failure (27.4.4.3)). If an exception was thrown while extracting a character, the function set failbit in error state, and if failbit is on in exceptions() the caught exception is rethrown.
9 Returns: *this. ~~~~~
Now, I think what I said about failing to read falls under the last bullet item in paragraph 7. But if no exception is thrown, and the buffer goes bad after reading and inserting several characters, the operation will be flagged as successful, I guess.
That's where I'm wrong, probably. You still need to test 'in' when returning the flag. Or not. Depending on what you consider a failure.
Also read paragraph 8. It says that if an exception is thrown while extracting a character, the function sets failbit in error state. Since a buffer only goes bad by throwing an exception,
Is that guaranteed? I didn't see it. Where is it defined?
All streaming I/O operations (both formatted and unformatted) only set
ios_base::badbit when an exception is thrown by a stream buffer. Do you
agree? This is really what I wanted to say. the function sets failbit on a bad read. It looks like you were right.
Since 'out << in.rdbuf()' fails on all errors, we need not test 'in'.
I'll take your word for it, if you substantiate it with a quote from the Standard :-)
I don't have a copy of the actual standard. I am relying on MSDN library
documentation, which makes life harder. :P This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Claudio Grondi |
last post by:
I would like to save time copying the same file
(>6 GByte) to various different target storage
media connected to the system via USB.
Is there a (Python or other) tool able to help me
to do...
|
by: SeanR |
last post by:
I have a function to copare two files. It will first copy the original file
form a different server to a local temp path and then compare that version to
a version that has been restored form tape....
|
by: Joshua Ginsberg |
last post by:
Howdy --
I have a class that has an attribute that is a dictionary that contains
an object that has a kword argument that is a lambda. Confused yet?
Simplified example:
import copy
class...
|
by: DraguVaso |
last post by:
Hi,
I need a SECURE way to copy parts of a file. I'm having files which contains
a whole bunch of records. In one 'fysical' file I'm having one or more
logical files.
What I need to do is to...
|
by: luis molina Micasoft |
last post by:
it seems that when i do file.copy the svchost.exe is hanged, i mean if i make
40 threads of file.copy , 40 copys of files at same time the system is going
down and stop responding, this is when i'm...
|
by: lgbjr |
last post by:
Hello All,
I¡¯m using a context menu associated with some pictureboxes to provide
copy/paste functionality. Copying the image to the clipboard was easy. But
pasting an image from the clipboard...
|
by: Emin |
last post by:
Dear experts,
I got some unexpected behavior in getattr and copy.deepcopy (see
transcript below). I'm not sure if this is actually a bug in
copy.deepcopy or if I'm doing something too magical...
|
by: ajc308 |
last post by:
I'm attempting to sort the <file>s within each <directory> in my XML according to their file extension, then write out the resulting sorted data back to XML format. I had it working before, and when...
|
by: maheshkadam |
last post by:
Hi friends
I am new to perl so please guide me.
I have one application which created backup log file every day.But it appends that file so you can see logs for different day in one file only.
...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
| |