I have a problem when handling the txt file in C++.
My code is like this, and the test.txt file is in the attachment.
there are two functions:

  1. int txtnum(ifstream& input, char* filename ) is to count the amount of numbers list in the txt file.
  2. long filesize( ifstream& input,char* filename) is to calculate the txt file size (in bytes)

my problem is, after call the first function in main( ). I can't get the file size by function 2.(exactly it return 0 for the filesize) why?

#include <iostream>
#include <fstream>
using namespace std;

int txtnum(ifstream& input, char* filename ){
	input.open(filename);
	int c;
	int count = 0;
	input>>c;
	while (!input.eof())
	{
/*		cout<<c<<endl;*/ //test the out put
		if (!isdigit(c))
		{
			count++;
		}
		input>>c;
	}
/*	input.seekg(0,ios::beg);*/
	input.close();
	return count;
}

long filesize( ifstream& input,char* filename){
	input.open(filename);
	if (input.is_open( ))
	{
		input.seekg(0,ios::beg);
		long begin, end; 
		begin = input.tellg();
		cout<<"begin ="<<begin<<endl;
		input.seekg(0,ios::end);
		end = input.tellg();
		cout<<"end= "<<end<<endl;
		
		input.close();
		return (end-begin);
	}
	return -1;	
}
int main(){


	ifstream input;
	char *file="test.txt";
	int vb = txtnum(input, file);
	cout<<vb<<endl;
	
	cout<<filesize(input,file)<<endl;
	return 0;
}

After calling the first function you have to clear the stream's eof() error bit. input.clear(); should fix the problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.