Outputting to file from multiple functions

I'm having a problem where I don't know how I can output to a single file from multiple functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//Example code
#include<iostream>
#include<fstream>
void hi()
{
ofstream myfile;
myfile.open ("assignment.txt");
myfile<<"Hi"<<endl;
return 0;
}
int main()
{
ofstream myfile;
myfile.open ("assignment.txt");
if (myfile.fail())
	{ 
		cout<<"error"<<endl;
		exit(1);
	}
for (int i = 0; i<3; i++)
{
hi();
}
hi();
myfile<<"Hello!"<<endl;
myfile.close();
return 0;
}


I'm only getting the "Hello!" from my file; I'm not seeing the "Hi" from my void function.
Last edited on
The simplest way is to pass the reference to the opened file to the function.

1
2
3
4
void hi( std::ofstream &os )
{
   os<<"Hi"<<endl;
}



and in main call the function the following way

hi( myfile );

i think you know about the put-pointer.
it states where the next output operation will take place.
you must know that myfile in main() is a totally different object than the one in hi().

each time you call hi(), the myfile is constructed again and opens the file for output operations, this removes previous data stored in that file and then writes the word Hi to that file.

after the 4 calls to hi(), you try to write the word Hello to that file, the problem is you're trying to write it via the stream inside main(), this stream's put-pointer still points to the beginning of the file, that means the word Hello will overwrite the previous word existed in that file.

for the sake of demonstration, consider switching the work of hi(), let hi() print the word Hello and main()
calls hi() 4 times then writes the word Hi to the file, just as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//Example code
#include<iostream>
#include<fstream>
void hi()
{
ofstream myfile;
myfile.open ("assignment.txt");
myfile<<"Hello"<<endl;
return 0;
}
int main()
{
ofstream myfile;
myfile.open ("assignment.txt");
if (myfile.fail())
	{ 
		cout<<"error"<<endl;
		exit(1);
	}
for (int i = 0; i<3; i++)
{
hi();
}
hi();
myfile<<"Hi"<<endl;
myfile.close();
return 0;
}


the output file shall now contain:
Hillo

hope that was clear enough.
are you trying to append to file? i mean in your example are you exspecting "Hi Hi Hi Hi Hello!"?

If so open your file like this,
myfile.open("assignment.txt",ios:out | ios:app);
And make sure close file when you open it. Even in your hi() func.
Topic archived. No new replies allowed.