0

I have a c++ code(A.cpp) in which i am openening a file and writting some data to it as follows :

A.cpp
classA{};
A::A()
{
_start = clock();
}
A::~A(){
_end = clock();
complete_time = _end - _start;
total_time = total_time + complete_time;
std::ofstream myfile;
myfile.open("C:/target/test.txt");
myfile << "a.cpp execution time "<<total_time;
}

So here i get a file as test.txt having the execution time. Now there is another class in which i am doing the same as follows (B.cpp):

classB{};
B::B()
{
_start = clock();
}
B::~B(){
_end = clock();
complete_time = _end - _start;
total_time = total_time + complete_time;
std::ofstream myfile;
myfile.open("C:/target/test.txt");
myfile << "B.cpp execution time "<<total_time;
}

Following is the main section:

int main(){
 A ob;
 B obj;
 return 0;
}

So, now i get test.txt file as "a.cpp execution time 304" but there is no information regardging B.cpp execution time. so, please suggest how may i achieve this. I want to have a single test.txt file in which i get execution time of all of the classes of same solution, in the above solution there are only two classes there might be number of classes. So , please help.

Learner
  • 453
  • 13
  • 29

2 Answers2

2

When you open the output stream without any specific flags, std::ios::out is the default (see e.g. this std::ofstream::open reference).

Then if we continue to dig a little we come to std::filebuf::open, and if you see thaty reference it contains a table which says that std::ios::out by itself is the same as the C fopen function with the "w" mode, which truncates the file. I.e. if the file exists, the data inside it is discarded.

To append data to an existing file you need to use the std::ios::app open mode. Like this:

myfile.open("C:/target/test.txt", std::ios::out | std::ios::app);

Using this, if the file doesn't exist it is created, but if it does exist it's contents is preserved and each new write to the file will be done at the end, appending to the file.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

If it is a multi-threading environment, have to take care of locks, ref the thread @(Using std:fstream how to deny access (read and write) to the file)

Community
  • 1
  • 1
Rock
  • 23
  • 4