C++ 在文件对象的当前位置从文件中删除字符

C++ 在文件对象的当前位置从文件中删除字符,c++,fstream,C++,Fstream,请看这个最小的工作示例: #include <iostream> #include <fostream> using namespace std; int main() { fstream file; file.open("asd.txt", ios_base::out); file << "this is a sentence!" << endl; ///is it possible at this poi

请看这个最小的工作示例:

#include <iostream>
#include <fostream>

using namespace std;

int main()
{
    fstream file;
    file.open("asd.txt", ios_base::out);

    file << "this is a sentence!" << endl;

    ///is it possible at this point to delete the last character, the exclamation mark, from the file asd.txt using the object "file"?

    file.close();
    return 0;
}
#包括
#包括
使用名称空间std;
int main()
{
流文件;
打开(“asd.txt”,ios_base::out);

文件您可以使用
std::ofstream
seekp
write
来用空格覆盖!的内容(我试图删除!或用“\0”替换它,但似乎无法实现) #包括 #包括

int main()
{
    std::ofstream file;
    file.open("asd.txt");
    ///is it possible at this point to delete the last character, the exclamation mark, from the file asd.txt using the object "file"?
    //Yes!
    file.write("this is a sentence!", 19); // writes 19 chars to the file
    long pos = file.tellp(); // gets the current position of the buffer ( in this case 19)
    file.seekp(pos - 1); // subtracts one from the buffer position ( now 18 )
    // writes a space that is one char at the current position of the file ( 18, which overwrites the '!' that is in pos 19)
    file.write("", 1); 
    file.close();
    return 0;
}
尽管有很多选择,但您始终可以关闭文件,使用
std::ios_base::trunc
重新打开文件,这将清除文件中的所有内容,然后您只能在
之前再次写入字符串!

file.write(“这是一个句子!”,18);

您还可以将字符串存储在std::string中,并调用std::string::pop_back()删除最后一个字符,然后在清除文件内容后将其写入文件。只需将流存储到
std::ostringstream
中,然后从
ostringstream
获取
字符串
,然后
pop_back()
代码!


这实际上取决于您的用例,如果您想提供更多详细信息,我可以免费为您提供更多帮助。

这在C++17中可以使用resize_文件,否则我相信您必须“覆盖”您不想要的部分或一起重写文件。其他解决方案可能涉及特定于操作系统的API。否则,方法是将所有数据读取到字符串中,弹出最后一个字符,打开同名的干净文件并写入其中。问题出现在大型文件中。文件可能重复