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

时间:2017-05-05 16:33:57

标签: 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 point to delete the last character, the exclamation mark, from the file asd.txt using the object "file"?

    file.close();
    return 0;
}

我正在使用文件对象asd.txt向文件file写一个句子。是否可以使用!从<{1}}删除字符asd.txt

1 个答案:

答案 0 :(得分:0)

您可以使用std::ofstreamseekpwrite覆盖!有空格(我试过删除!或者替换为&#39; \ 0&#39;但我似乎无法让它工作)     #包括     #include

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重新打开文件,这将清除文件中的所有内容,然后你可以再次写入字符串,直到{{{ 1}}

!

您还可以将字符串存储在std :: string中并调用std :: string :: pop_back()以删除最后一个字符,然后在清除文件内容后将其写入文件。只需将流存储到file.write("this is a sentence!", 18);并从std::ostringstream获取string,然后ostringstream pop_back()

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