2012-03-27 107 views
1

我的代码有一个小问题。我一直试图从随机访问文件的末尾读取一些信息,然后在文件的开头重新定位光标。到目前为止,seekg一直没有工作。这里是我的代码:如何从文件的末尾移动到以C++开头

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); 
} 

回答

3

要转到文件的末尾:

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

要获得(在结束时),该文件的长度,用tellg这返回get指针的绝对位置。

length = is.tellg(); 

要返回到开始再次使用seekg,这台置入指针的位置。

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

如果你已经尝试过这个你能具体谈谈什么是不工作?

+0

使用'tellg'是否可以获得文件的长度(以及长度的定义)是非常依赖系统的,我不会依赖它。 – 2012-03-27 16:00:47

+0

我尝试了你所说的并替换了第一条语句。每当我尝试从文件中读取代码“InData.read(reinterpret_cast < char * >(&FileIn),sizeof(AssignData))”。但是,文件中的信息不会传递给“FileIn.DisplayFileContent()”,它将显示最后一行的内容 – OpalG 2012-03-27 16:04:02

相关问题