file writing/appending

How do you check if a file appended successfully or has written to a file successfully. I thought it would be something like this:

1
2
3
4
5
6
7
8
9
  //appending to file
  ofstream file;
  file.open("Text.txt", ios::out | ios::app)
  file << "string";
  //checkin to see if it appended successfully
  if(file.good())
     return true;
  else 
     return false;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
ofstream file;
errno_t ferror;
 ferror= file.open("Text.txt", ios::out | ios::app)
if(ferror !=0 )
{
  cout<<"append operation failed";
exit(0);
}
  file << "string";
  //checkin to see if it appended successfully
  if(file.good())
     return true;
  else 
     return false;


the file operations return different values to indicate different results, usually 0 is returned on success ,read more on individual operations to see what and all values they return
You orig fragment can be rewritten like this (I like complete functions...)

1
2
3
4
5
6
7
8
9
void test_append_to_file() {
  ofstream file("Text.txt", ios::out | ios::app);
  if ( !file.is_open() )
    return false; // exiting the app due to a file open failure is too draconian
 
  if (file << "string")
    return true;
  return false;
}


Andy

Note:

1. ofstream::open has a void return type
http://www.cplusplus.com/reference/fstream/fstream/open/
(so I'm not sure that the errno_t is about?)

2. exit() should be (almost always) avoided in C++ code
See response in this stackoverflow.com thread: return statement vs exit() in main()
http://stackoverflow.com/questions/461449/return-statement-vs-exit-in-main
Last edited on
void bool test_append_to_file() {
Topic archived. No new replies allowed.