所以,我有一个包含int值的二进制文件。所以int需要4个字节。
#include <iostream>
#include <cstdio>
using namespace std;
class IntFile
{
public:
//int index = 0;
int value;
FILE* file;
IntFile() {}
~IntFile() {}
int mnumbers[10];
int mnumbers2[10];
// get value from current index in file
int getValue(int index)
{
fseek(file, 4*index, SEEK_SET);
fread(&value, 4, 1, file);
return value;
}
friend struct Move;
struct Move
{
int index = 0;
int value = 0;
bool operator==(const Move&other) const
{
return index == other.index;
}
bool operator!=(const Move&other) const
{
return index!=other.index;
}
int &operator*()
{
return value = IntFile::getValue(int index); <- this thing does not work, I am getting errors like expected primary expressions..
}
Move&operator++()
{
this->index = index+1;
return *this;
}
Move&operator--()
{
this->index = index -1;
return *this;
}
};
Move begin()
{
fseek(file, 0, SEEK_SET);
//index = 0;
}
Move end()
{
fseek(file, 0, SEEK_END);
//index = 9;
}
};
int main()
{
IntFile file;
int A;
for ( int i = 0; i < 10; i++)
{
file.mnumbers2[i] = 0;
cout << file.mnumbers2[i] << " "; // make every element of array = 0
}
file.file = fopen("text.txt", "r+b");
for (IntFile::Move Iter = file.begin(); Iter != file.end(); ++Iter)
{
fread(file.mnumbers2,4,1,file.file);
cout << " I " << endl;
//cout << "Iterator: " << Iter;
}
cout << endl;
A = file.getValue(5);
cout << "A: " << A << endl;
for ( int i = 0; i < 10; i++)
{
cout << file.mnumbers2[i] << " ";
}
////////////////////////////////////////
fclose(file.file);
return 0;
}
但我没有进入这个循环
for (IntFile::Move Iter = file.begin(); Iter != file.end(); ++Iter)
{
fread(file.mnumbers2,4,1,file.file);
cout << " I " << endl;
//cout << "Iterator: " << Iter;
}
在begin()
中,我们将光标放在文件的乞讨位置,最后end()
显然,光标应该在文件的末尾。我的那个不起作用。
你能给我什么提示吗?我基本上需要operator*
和begin(), end()