std :: ofstream,覆盖错误的文件行
std::ofstream, Overwriting wrong file line
我有一个将数据输出到文本文件的函数:
void File_IO::save( const std::string& path_ ) const
{
const std::string file_name = path_ + this->local_time() + ".txt";
std::ofstream outfile( file_name );
std::vector<std::string> vec = { "One", "Two", "Three", "Four" };
outfile << 'n' << 'n' << "//--------------------------------- DATA:" << 'n' << 'n';
long pos_beg = outfile.tellp();
for( auto& i : vec )
{
outfile << i << 'n';
}
long pos_end = outfile.tellp();
outfile << 'n' << "//---------------------------------------" << 'n' << 'n';
//outfile.seekp( 0 );
//outfile << pos_beg << " " << pos_end << " " << pos_beg << " " << pos_end;
}
输出:
//--------------------------------- DATA:
One
Two
Three
Four
//---------------------------------------
当涉及数据的开始/结束位置覆盖第一行时,问题发生在功能的末尾...添加这两行:
outfile.seekp( 0 );
outfile << pos_beg << " " << pos_end << " " << pos_beg << " " << pos_end;
输出:
49 72 49 72---------------------------- DATA:
One
Two
Three
Four
//---------------------------------------
如您所见,在到达标头之前,文件中有两个空行,但是它覆盖了这些,并部分删除了标题行,这是文件中的第三行,而不是预期的第一个行。
另一个线索:
如果我只写一个var,它似乎可以工作,但仍删除文件开始时的一个空行:
outfile.seekp( 0 );
outfile << pos_beg ;
输出:
49
//--------------------------------- DATA:
One
Two
Three
Four
//---------------------------------------
有人可以解释这里发生的事情,以及如何根据需要编辑功能工作?
ps不允许我出于某种原因添加相关标签
在正确方向上igor轻推的背面,将以下代码行添加到函数中似乎有效:
outfile << " " << 'n';
修订的功能:
void File_IO::save( const std::string& path_ ) const
{
const std::string file_name = path_ + this->local_time() + ".txt";
std::ofstream outfile( file_name );
std::vector<std::string> vec = { "One", "Two", "Three", "Four" };
// Edit
outfile << " " << 'n';
// Edit
outfile << 'n' << 'n' << "//--------------------------------- DATA:" << 'n' << 'n';
long pos_beg = outfile.tellp();
for( auto& i : vec )
{
outfile << i << 'n';
}
long pos_end = outfile.tellp();
outfile << 'n' << "//---------------------------------------" << 'n' << 'n';
outfile.seekp( 0 );
outfile << pos_beg << " " << pos_end << " " << pos_beg << " " << pos_end;
}
输出:
104 127 104 127
//--------------------------------- DATA:
One
Two
Three
Four
//---------------------------------------
如果有人可以提供更好的答案并说出为什么,我会接受我的那个似乎有点幼体。
相关文章:
- C++系统找不到指定的文件错误
- C++语法头文件错误
- C++生成文件错误"implicit entry/start for main executable"
- C++/生成文件错误:未定义对"main"的引用
- VS2019:资源文件错误:中性(默认)(未知子语言:0x8)
- C++程序不制作文件(错误)
- 安卓工作室 |CPP 文件错误错误: 位图库中对"AndroidBitmap_unlockPixels"的未定义引用
- "what does ":*** [可执行文件] 错误 1 " mean ?"
- 如何修复使用VScode调试器gcc调试时的"找不到文件"错误
- 在课堂上创建了一个朋友,给出"无输入文件"错误
- Qt .exe文件错误
- c++ 添加具有写入文件错误的文本变量
- 无法转换 .CATPart 文件.错误:输入文件路径似乎包含不支持的字符
- 写入文本文件错误,QT
- C++写入文件错误
- Windows Subsystem for Linux (WSL) 下的间歇性随机"找不到文件"错误
- 犰狳读取MAT文件错误
- 无法求解FullPathForFilename:COCOS2DX中可能缺少文件错误
- C Wininet FTP列出了许多文件错误
- 生成文件错误 - 找不到文件 - *.cpp