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

C++: ifstream file pointer not getting reset

Hi,

I have the following piece of code. I do the following here

1)open a file.
2) Print the filepointer positon . I get 0
3)Read the file in a while loop till i reach the end
4)close the file
5)Open the same file
6) Print the file pointer position I get -1.( I expect 0 here)

Can anyone let me know the reason for this error and how is it possible to avoid this.

Thanking you in advance
Samarth

#include <fstream>
#include <iostream>

using namespace std;
int OpenFile(fstream  &fileHandle, char * fileName)
{
	cout << "Opening File" << endl;
	int success = true;
	
	// Open the file and read the data
	fileHandle.open(fileName, ios::in|ios::binary);
	
	// Check if the file is present
	if (!fileHandle.is_open())
	{ 
		// File is not present. Log the information
		cout << "OpenFile::Error opening file "<< endl; 
		success = false;
	}
	
	return success;
}

int ReadFile(char *buf, fstream  &file)
{
	while(!file.eof())
	{
		file.read(buf, 1024);
	}
}

int main()
{
	fstream file;
	OpenFile(file, "1.mpg");
	cout << "tellg " << file.tellg()<< endl;
	
	char buf[1024];
	ReadFile(buf,file);
	file.close();
	
	//file = new ifstream();
	OpenFile(file, "1.mpg");
	cout << "tellg " << file.tellg()<< endl;
	
	return 1;
}
samarth
Newbie Poster
2 posts since Feb 2005
Reputation Points: 10
Solved Threads: 0
 
frrossk
Posting Whiz in Training
220 posts since Sep 2004
Reputation Points: 17
Solved Threads: 9
 

The problem may be in the bits of the stream. Have you try file.clear()?

gastonci
Light Poster
34 posts since Aug 2009
Reputation Points: 10
Solved Threads: 4
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You