如何在c++中从文件的末尾移动到开头

How to move from the end of the file to the beginning in c++

本文关键字:移动 开头 文件 c++      更新时间:2023-10-16

我的代码有一个小问题。我一直在尝试从随机访问文件的末尾读取一些信息,然后将光标重新定位在文件的开头。到目前为止,seekg还没有发挥作用。这是我的代码:

void main ()
{
    AssignData FileOut;
    AssignData FileIn;
    ofstream OutData("Data.dat", ios::out | ios::app | ios::binary);
    ifstream InData("Data.dat", ios::in);
    cout <<"Writing to file" << endl;
    if (!OutData)
    {
         cout<<"File does not exist"<<endl;
     exit(1);
    }
    //read through file
    while (InData.read( reinterpret_cast< char * >( &FileIn ),sizeof( AssignData ) ))
    {                        
    }
    FileIn.DisplayFileContent();//displays the last line in the file
    FileOut.setInfo();//allows user to add another record
    //Writes record to file
    OutData.write( reinterpret_cast< const char * >( &FileOut ), sizeof(AssignData) );                                        
    OutData.close();
    cout << endl<<endl;
    //Reads the first record from the file
    InData.seekg(0);
    while (InData.read( reinterpret_cast< char * >( &FileIn), sizeof(AssignData) ))
    {
    // display record
        if ( (FileIn.getID() != 0) || (FileIn.getID()!=NULL) )
    {
        FileIn.DisplayFileContent();
    }                         
    }
    InData.close();
    _getch();
    exit(0);
}

转到文件末尾:

ifstream is;
is.open( "file.txt", ios::binary );
is.seekg (0, ios::end);

要获取文件的长度(当位于末尾时),请使用tellg,它返回获取指针的绝对位置。

length = is.tellg();

要返回到开头,请再次使用seekg,这将设置放置指针的位置。

is.seekg (0, ios::beg);

如果你已经尝试过了,你能更具体地说什么不起作用吗?

您可能想要"seekg(ios_base::beg)":

http://bytes.com/topic/c/answers/602553-ifstream-seeking

http://www.cplusplus.com/reference/iostream/istream/seekg/

如果它"不起作用",有两件事可以尝试:

1) 检查位置"tellg()"

2) 检查错误状态(eofbit、failbit、badbit)