如何在c++中从文件的末尾移动到开头
How to move from the end of the file to the beginning in c++
我的代码有一个小问题。我一直在尝试从随机访问文件的末尾读取一些信息,然后将光标重新定位在文件的开头。到目前为止,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)
相关文章:
- 将对象移动到std::shared_ptr
- 何时在引用或唯一指针上使用移动语义
- 如何从具有移动语义的类对象中生成共享指针
- 将shared_ptr移动到<StructA>shared_ptr<变体<结构A、结构 B>>
- C / C++ 移位/偏移/向左或向右移动位图?
- MSVC将仅移动结构参数解释为指针
- 自定义先决条件对移动分配运算符有效吗
- 返回值优化:显式移动还是隐式
- 当有分配器意识的容器被复制/移动时,反弹分配器是否被复制/移走
- 为什么复制而不是移动数据元素?
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 可以使用移动语义更改或改进此C++代码吗?
- 使lambda不可复制/不可移动
- 设计将引用元素移动到开头的数据结构.C++
- C++将值移动到数组的开头
- 我可以从向量的开头移动对象吗?为什么不呢
- 在数组的开头添加一个元素并移动其余元素,但保留大小
- 将 vector<vector> 的最后一个元素移动到<int>开头
- 如何在c++中从文件的末尾移动到开头
- 如何移动数组中的元素,将奇数放到数组的开头(从最小到最大),甚至放到后面(从最大到最小)