0

I have created a library which has a portion of code similar to following

int a;
a = 5;

std::ofstream outFile("File.txt");
outFile << "Values : " << std::endl;
outFile << a << std::endl;

Now, this library is used by two different process which outputs File.txt with two different outputs

Output 1 :

Values :

Ouptut 2 :

Values :
5

I've found some resources where its mentioned to pass integers to streams by converting to strings using std::to_string (Converting integer to string in c++) . But I want to know what makes the two processes act differently in the same scenario. It feels like as if one of the process do some changes to the streams in a global state

BAdhi
  • 420
  • 7
  • 19
  • 2
    Without a [mcve] it's impossible to help you (except to wildly guess). Please take some time to review [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Jan 03 '19 at 09:37
  • 2
    On Linux if two processes are trying to write to same file, result is undefined. If you append PID to file-name, you will get correct output. – g-217 Jan 03 '19 at 09:38

1 Answers1

1

Try running the two different processes in different directories. From what you've shown, more than likely, they both are trying to access the same file. This isn't something you can do. Check out this post which talks about why trying to use threads to open the same file twice at the same time doesn't work.

  • thanks for the reply. but these processes was run one after the other. So there wasnt a doubt about writing the same file concurrently – BAdhi Jan 03 '19 at 16:36
  • Did you use the close function to make sure the first process doesn't keep the file open? – Dawson Moore Jan 03 '19 at 16:42