如何在.dat
文件中返回项目的位置?
在search()
函数中我试图在fractions.dat
文件中找到一个项目并将其返回给用户。但是,该函数始终返回-2(返回的变量初始化为最初的值)。
执行if
语句,但似乎file.read(...)
未将cur
设置为任何内容。
#include <iostream>
#include <fstream>
using namespace std;
struct Fraction
{
int num, den;
};
int search(fstream& file, Fraction* f);
int menu();
void proccessChoice(int i);
Fraction* readFrac();
Fraction* fracs[100];
int index;
string fileName = "fractions.dat";
fstream file(fileName, ios::in | ios::out | ios::binary);
int main()
{
if (!file)
{
cout << "Error opening file. Program aborting.\n";
system("pause");
exit(1);
}
int choice;
do
{
choice = menu();
proccessChoice(choice);
} while(choice != 3);
system("pause");
return 0;
}
int menu()
{
int c;
cout << "1.Enter new fraction" << endl;
cout << "2.Find fraction location" << endl;
cout << "3.Quit" << endl;
cin >> c;
return c;
}
void proccessChoice(int i)
{
switch(i)
{
case 1:
{
cout << "Please enter a fraction to be stored: ";
fracs[index] = readFrac();
file.write(reinterpret_cast<char*>(fracs[index]), sizeof(Fraction));
/*cout << fracs[index]->num << "/" << fracs[index]->den ;*/
index++;
}
break;
case 2:
{
cout << "Please enter a fraction to find: ";
Fraction* fToFind = readFrac();
int i = search(file, fToFind);
cout << "The fraction is at position: "<< i << endl;
}
break;
}
}
int search(fstream& file, Fraction* f)
{
Fraction* cur = new Fraction();
int pos = -2;
if (!file)
{
cout << "Error opening file. Program aborting.\n";
system("pause");
exit(1);
}
while(!file.eof())
{
file.read(reinterpret_cast<char *>(cur), sizeof(Fraction));
if((cur->num == f->num) && (cur->den == f->den))
{
cout << "\nFrac found!" << cur->num << "/" << cur->num<<endl;
pos = file.tellg();
return pos;
}
}
return pos;
}
Fraction* readFrac()
{
Fraction* f = new Fraction();
char slash;
cin >> f->num >> slash >> f->den;
return f;
}
答案 0 :(得分:2)
您没有从文件开头开始搜索。你需要:
file.seekg( 0, std::ios::beg );
同样地,我认为在写入文件时你并没有追加到底。 p>
file.seekp( 0, std::ios::end );