file pointers

If you have a pointer to a file/file stream like this: ifstream *file.
do you open and close a file like this:
1
2
3
file->open("Input.txt");

file-> close();


Can you read from the file by saying:
1
2
3
4
5
6
7
getline(*file, input) //input is string to store files contents

while(*file)
{
    //do comparisons
    getline(*file, input)
}
Yes as long as file points to a valid ifstream object.

Are you sure you have to use pointers? They often just complicate things, and should not be used unless you have a good reason to.
Ya, i have to use pointers...the task brief says to implement functions in a class and i have ifstream* file as a private variable.

Thing is the code i have compiles but when i run it, it gives me segmentation fault
Can you perhaps show how you set the file pointer to point at the ifstream object?
I'm not sure i did that or i know how to do that, all i did was try to open the file just as shown above
file is just a pointer. To be able to call the ifstream functions you need an ifstream object.

I guess you are supposed to create the object with new?
 
file = new std::ifstream;

and then use delete to destruct the ifstream object when you no longer need it.
 
delete file;
i have tried what you have suggested...but i doubt my code reads every line from the file as i only get one line which is somewhere in the middle as output.
In the code below i am trying to open and the file and to check if file is really open

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
	void fileOpen(string fileName)    
		{
			string word;
			file->open(fileName.c_str(), ios::in );
			if(file)
			{
				getline(*file,  word);
				while(file)
				{
					cout << word;
					getline(*file, word);
				}
			}
			
			else
				cout << "File not open";
		}
You print no newlines so the whole file will be printed on one line.
Topic archived. No new replies allowed.