如何让'read'函数从文件的开头开始?

How to make the 'read' function start from the beginning of the file?

本文关键字:开头 开始 文件 read 函数      更新时间:2023-10-16

我正在尝试读取一个二进制文件,并且正在使用f_in.read((char(*) &tmp, sizeof(tmp))函数。然而,每次我调用这个函数时,它都会从上一个读取函数停止的位置继续读取文件。每次调用读取函数时,是否可以使其从文件的开头开始?

打开pixmap.bin文件:

int main(){
    ifstream f_in;
    f_in.open("Pixmap.bin", ios::binary);
    if (f_in.fail()) {
        cerr<<"Error while opening the file pixmap.bin"<<endl;
        f_in.close();
        exit(EXIT_FAILURE);
    }

我想每次从头开始读取时使用的功能:

void Read_Dimensions(ifstream &f_in, int Dimensions[2]) {
    uint tmp(0);
    for(int i=0; i<2;i++) {
        f_in.read((char*) &tmp, sizeof(tmp));
        Dimensions[i]=tmp;
    }
    }

这是相对于文件指针的,请尝试在"文件指针"部分中读取此页:http://www.eecs.umich.edu/courses/eecs380/HANDOUTS/cppBinaryFileIO-2.html

这里的例子给出:

int main()
{
  int x;
  streampos pos;
  ifstream infile;
  infile.open("silly.dat", ios::binary | ios::in);
  infile.seekp(243, ios::beg); // move 243 bytes into the file
  infile.read(&x, sizeof(x));
  pos = infile.tellg();
  cout << "The file pointer is now at location " << pos << endl;
  infile.seekp(0,ios::end); // seek to the end of the file
  infile.seekp(-10, ios::cur); // back up 10 bytes
  infile.close();
}

希望对你有所帮助。