0

编辑:这个问题将被编辑,请停止阅读。不要浪费你的时间!谢谢

我正在做高中 Turbo C++。我尝试制作一个包含搜索二进制文件的函数的头文件。我的头文件程序是: alpha.h

#ifndef ALPHA_H
#define ALPHA_H

#if !defined __FSTREAM_H
#include<fstream.h>
#endif

#if !defined __PROCESS_H
#include<process.h>
#endif

void searchclass(char* & buf, int, char *);

#endif

根据我在互联网上所做的一些研究,我发现定义将放在一个单独的程序中,而不是在主头文件中。这就是那个程序:ALPHA.CPP

#include<process.h>
#include<fstream.h>
#include"alpha.h"

//All the Definations of the alpha.h header file go here

void searchclass(char* & buf, int s_var, char * file)
{
    ifstream fin;
    fin.open(file, ios::binary);
    if(!fin)
    {
    cout<<"Error 404: File not found";
    exit(-1);
    }
    while(!fin.read((char*)buf, sizeof(buf)))
    if(buf.getint()==s_var)
        cout<<"\n\nRecord Found!";
        buf.show();
    fin.close();
}

请记住,我正在尝试编写一个函数,该函数可以帮助我搜索以类的形式存储记录的随机二进制文件,以查找某些特定的int 变量。所以它应该能够接收任何类的对象并在其中执行搜索。

这是我为检查头文件而编写的程序。 A_TEST.CPP

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include"alpha.h"
#include<string.h>

class stu
{   int rn;
    char name[20];
public:
void show()   //Display Function
{
   cout<<"\n\tStudent Details:";
   cout<<"\nName: "<<name;
   cout<<"\nRoll No.: "<<rn;
}
stu()       //constructor
{
  rn = 6;
  strcpy(name,"Random Name");
}
int getint()            //return function
{ 
  return rn; 
}
};

char* returnfile()
{ char file[10];
  strcpy(file,"file.dat");
  return file;
}

void main()
{
    clrscr();
    int search_var=6;
    stu S1;
    char file[10];
    strcpy(file, "test.dat");
    ofstream fout;
    fout.open(file, ios::binary);
    fout.write((char*)&S1, sizeof(S1));
    fout.close();

    searchclass((char*)& S1, search_var, file);

    getch();
}

在编译 A_TEST.CPP(上面的程序)时,我收到警告:

警告 A_TEST.CPP 45:在调用 'searchclass(char * &,int,char *)' 时临时用于参数 'buf'

在链接时,它给了我这个错误:

链接 A_TEST.EXE

链接器错误:模块 A_TEST.CPP 中未定义的符号搜索类(char near near&,int,char near

我认为 ALPHA.CPP 文件没有与 alpha.h 文件链接,如果我编译 ALPHA.CPP 文件,它会给我以下错误:

错误 ALPHA.CPP 17:左侧需要结构。或者 。*

错误 ALPHA.CPP 19:左侧需要结构。或者 。*

警告 ALPHA.CPP 21:从未使用参数“s_var”

4

1 回答 1

0

在 ALPHA.CPP 17 和 19 中,您不能编写这样的代码,因为 int 类型没有 getint() 或 show() 方法。如果要检查缓冲区中的 int,则应先将指针转换为“int*”,尝试以下代码:

int count = fin.read((char*)buf, sizeof(buf));
for (int i = 0; i<(count-4); ++i) {
    if (*(int *)(buf + i) == s_var) {
        cout << "\n\nRecord Found!";
        break;
    }
}
于 2017-04-01T07:49:18.110 回答