954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Help in passing ifstream object to another function

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;
	file.open("test.txt");

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

	std::string line;
	while(std::getline(file,line))
		std::cout << line << std::endl;

	test(file);

return 0;
}

bool test(std::ifstream& FILE){

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

	std::string line2;
	while(std::getline(FILE,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

Hi
How
       are you?


And in here is the output

It's open in main()
Hi
How
       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

Sismetic
Newbie Poster
6 posts since Jul 2010
Reputation Points: 10
Solved Threads: 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

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: