如何在开头没有换行符的情况下附加到 .txt 文件?

问题描述 投票:0回答:1
#include <fstream>
#include <ctime>

int buyOut = 3434;

std::ofstream data("data.txt", std::ios::app);
        if (data.is_open()) {
            data << buyOut << "\n";
            data.close();
}

当“买断 " 附加到“data.txt”,它总是附加在文件的新行中,即使文件中的最后一个字符不是新行。

所以如果文件的内容是:Test123

新字符串应附加在此处:

Test123(这里)

(不在这里)


如何在 C++ 中实现这个?

c++
1个回答
0
投票

#包括 #包括

int 买入 = 3434;

std::ofstream 数据("data.txt", std::ios::app);

if (data.is_open()) { std::streampos pos = data.tellp();

if (pos != 0) {
    data.seekp(pos - 1);
}

data << buyOut << "\n";
data.close();

}

© www.soinside.com 2019 - 2024. All rights reserved.