我试图通过一个加 1 的 long 来找到文件的长度,直到到达文件末尾。它确实到达文件末尾,然后读取 EOF 就好像它是另一个值一样,导致它变为 -1。我不太清楚如何阻止这种情况发生并获取文件的实际长度。任何帮助,将不胜感激!
我的代码,目前:
#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;
}
}
输出:
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
最佳答案
你的逻辑有点不对。 tellg()
不会返回 EOF,直到 在 文件末尾的 get()
之后。请注意 get()
会更改文件位置,但您的循环条件是 tellg()
在读取之前 and 您调用 tellg ()
再次 after 读取期望它与读取之前相同 - 但它不会。
事实上还有更简洁的方法可以做到这一点,如果你想用你的方法来做到这一点,你的逻辑将是这样的(有点伪代码-y):
Last = 0;
while(InpFile.get()!=EOF)
{
Last = InpFile.tellg();
}
cout << Last << endl;
请注意,您的 seekg()
是不必要的,因为它将文件指针置于它已经存在的位置,我已将其删除以简化。
上面示例中的关键是您在读取之后 获取文件位置,但在到达 EOF 时不要覆盖 Last
。我们检查 get 而不是 tellg 返回的 EOF 状态。
想象一个 2 或 3 字节的小文件,并在脑海中或纸上处理您的原始代码,以更清楚地了解逻辑问题。
关于c++ - 用tellg()判断文件长度,最终结果为-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26834310/