c++ - 如何返回 .dat 文件中的项目索引?

标签 c++ fstream

如何在 .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;
}

最佳答案

您没有从文件的开头开始搜索。你需要:

file.seekg( 0, std::ios::beg );

同样,我认为您在写入文件时没有追加到末尾。

file.seekp( 0, std::ios::end );

关于c++ - 如何返回 .dat 文件中的项目索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13737964/

相关文章:

c++ - 使用 void_t 的多个 SFINAE 类模板特化

c++ - fstream包含ofstream和ifstream的所有内容?

c++ - 从文件读取到不同的类对象

c++ - 使用异常检查 C++ 流时出错

c++ - 如何在不使用连接功能的情况下连接信号和插槽?

c++ - 将 char 类型转换为 Unsigned short

c++ - 验证左括号和右括号的数量

c++ - 顺序容器和迭代器算法

c++ - 使用文件 - 替换一行

c++ - I/O 流字符串操作(正确的 Cin/cout 运算符 <</>>)