使用tellg()确定文件的长度,最终结果为-1
Determining length of file with tellg(), end result is -1
我试图通过一个增加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()
直到文件末尾的get()
之后的才会返回EOF。请注意,get()
会更改文件位置,但循环条件是读取之前的tellg()
,并且您在读取之后再次调用tellg()
,期望它与读取之前相同,但不会。
事实上,除了有更干净的方法之外,如果你想用你的方法来做这件事,你的逻辑应该是这样的(有点伪代码):
Last = 0;
while(InpFile.get()!=EOF)
{
Last = InpFile.tellg();
}
cout << Last << endl;
请注意,您的seekg()
是不必要的,因为它将文件指针放在它已经所在的位置,为了简化起见,我已经删除了它。
上面示例中的关键是,您在读取之后获得文件位置,但在达到EOF时不要覆盖Last
。我们检查get而不是tellg返回的EOF状态。
想象一个2或3字节的小文件,在脑海中或纸上处理原始代码,以更清楚地了解逻辑问题。
tellg返回当前字符的位置。如果失败,则返回-1。根据您的示例,您可以在迭代流时增加变量,或者使用@NeilKirk的链接
也许这不是你想要的答案,但为什么不使用stat()呢?请参阅如何确定C中文件的大小?
关于您的代码,您必须在指定EOF(EOF=-1)之前输出tellg()值
void ErrChek(ifstream &InpFile,long &Last,char &Read)
{
while((Last = InpFile.tellg())!=EOF)
{
cout << Last << endl;
InpFile.seekg(Last,ios::beg);
InpFile.get();
}
}
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- 用C++20 fmt限制结果的总大小
- 如何返回一个类的两个对象相加的结果
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 序列化,没有库的整数,得到奇怪的结果
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 在更改for循环的第三部分后,未使用for循环结果
- 使用++运算符会导致意外的结果
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- C++Brute Force攻击函数不会返回结果
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 算术运算的结果类似于:C浮点变量中的1/3
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 密码登录程序将永远循环并显示不正确的结果
- 如何让C++'tally up'结果并制定计划?
- 为什么函数 tellg() 没有返回好的结果?
- 使用tellg()确定文件的长度,最终结果为-1