Well, I have a test program, in which I wanted to test if it was possible to open a textfile(text.txt) for input, display it via cout, then passing the object via reference to another function, in it and display the file again(which should already be open,which is the whole point).

The thing is that, it does show it's open(via is_open()), but it doesnt display anything, inside the test() function, but it does inside the main() function. I would like for someone to help me make this program to display the input file inside the test() function.

Here is the code

#include <iostream>
#include <string>
#include <fstream>
//The map is for future use, right now Im just focused on passing the object succesfully.
#include <map>
#include "windows.h"

bool test(std::ifstream& file);

int main(){

	std::ifstream file;

	if( file.is_open() )
		std::cout << "It's open in main()" << std::endl;

	std::string line;
		std::cout << line << std::endl;


return 0;

bool test(std::ifstream& FILE){

		std::cout << "It's open in test()" << std::endl;

	std::string line2;
		std::cout << "Random text, just to see if it is printing any text at all" << line2 << std::endl;

	return true;


test.txt just contains

       are you?

And in here is the output

It's open in main()
       are you?
It's open in test()
Press any key to continue

I dont understand what Im doing wrong, why it doesn't display "Hi How are you?" again, and only It's open in test(), can somebody please help me out?

PS:As a compiler I use Microsoft Visual C++ 6.0

Aftrer main() finishes that loop reading the file the ifstream is located at end-of-file. Therefore test() can't read the file again. In test() call fseekp() to reset the file pointr back to beginning of file

This article has been dead for over six months. Start a new discussion instead.