I'm trying to find the length of a file through a long that increases by 1 until the end of the file is reached. It does go to the end of the file, then reads EOF as if it were another value, causing it to become -1. I can't quite figure out how to stop that from happening and get the actual length of the file. Any help would be appreciated!
My code, currently:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
void input(ofstream&,string &InputStr);
void ErrChek(ifstream&,long&,char&);
int main(int argc, const char * argv[])
{
char file2[] = "file2.txt";
ofstream OutFile;
ifstream InpFile;
string InputStr;
char Read;
int Choice = 0;
long Last = 0;
OutFile.open(file2);
if(OutFile.fail())
{
cout << "file named can not be found \n";
exit(1);
}
input(OutFile,InputStr);
OutFile.close();
InpFile.open(file2);
cout << InpFile.tellg() << endl;
if(InpFile.fail())
{
cout << "file named can not be found \n";
exit(1);
}
ErrChek(InpFile,Last,Read);
InpFile.close();
return 0;
}
void input(ofstream &OutFile,string &InputStr) //Gets input from user + writes to file
{
cout << "Please input 1 sentence for use in the file: ";
getline(cin,InputStr);
OutFile << InputStr;
}
void ErrChek(ifstream &InpFile,long &Last,char &Read)
{
while((Last = InpFile.tellg())!=EOF)
{
InpFile.seekg(Last,ios::beg);
InpFile.get();
Last = InpFile.tellg();
cout << InpFile.tellg() << endl;
}
}
The output:
Please input 1 sentence for use in the file: Test Sentence
0
1
2
3
4
5
6
7
8
9
10
11
12
13
-1