C++删除txt文件中的最后一个字符
C++ delete last character in a txt file
我需要一些帮助来删除txt文件中的最后一个字符。例如,如果我的txt文件包含1234567,我需要用C++代码删除最后一个字符,使文件变成123456。谢谢大家。
在可移植代码中实现这一点的唯一方法是读入数据,并写出除最后一个字符之外的所有字符。
如果您不介意不可移植的代码,大多数系统都提供了截断文件的方法。传统的Unix方法是查找文件的结束位置,然后在该位置向文件写入0字节。在Windows上,可以使用SetEndOfFile。其他系统将使用不同的名称和/或方法,但几乎所有系统都具有某种形式的功能。
对于一个可移植的解决方案,应该采用以下方法:
#include <fstream>
int main(){
std::ifstream fileIn( "file.txt" ); // Open for reading
std::string contents;
fileIn >> contents; // Store contents in a std::string
fileIn.close();
contents.pop_back(); // Remove last character
std::ofstream fileOut( "file.txt", std::ios::trunc ); // Open for writing (while also clearing file)
fileOut << contents; // Output contents with removed character
fileOut.close();
return 0;
}
这里有一个更健壮的方法,根据Alex Z的答案:
#include <fstream>
#include <string>
#include <sstream>
int main(){
std::ifstream fileIn( "file.txt" ); // Open for reading
std::stringstream buffer; // Store contents in a std::string
buffer << fileIn.rdbuf();
std::string contents = buffer.str();
fileIn.close();
contents.pop_back(); // Remove last character
std::ofstream fileOut( "file.txt" , std::ios::trunc); // Open for writing (while also clearing file)
fileOut << contents; // Output contents with removed character
fileOut.close();
}
诀窍在于这些行,它允许您有效地将整个文件读取到字符串中,而不仅仅是一个令牌:
std::stringstream buffer;
buffer << fileIn.rdbuf();
std::string contents = buffer.str();
这篇文章的灵感来源于Jerry Coffin在这篇文章中提出的第一个解决方案。这被认为是最快的解决方案。
如果输入文件不是太大,可以执行以下操作:-
1. Read the contents into a character array.
2. Truncate the original file.
3. Write the character array back to the file, except the last character.
如果文件太大,可以使用临时文件而不是字符数组。不过会有点慢。
相关文章:
- 使用连续分隔符和空最后一个字符进行拆分
- 如何检查字符串中的最后一个字符是否是某个字符并将其从字符串中删除?(C++)
- 比较最后一个字符,不区分大小写(带谓词?
- 在弦乐器中删除最后一个字符
- 输入文件中的第一个字符是输出文件中的最后一个字符,反之亦然
- 在C 字符串中,为什么在最后一个字符之后,通过索引和()访问索引时行为是不同的
- 如何查看复杂度为 O(1) 的字符串流对象中的最后一个字符
- 最后一个字符行编辑
- 如何在C 中获得字符串的最后一个字符
- 如何在C++中删除 UTF-8 字符串的最后一个字符
- 如何获取输入文件的行的第二个和最后一个字符,并在C++中组成数组
- 输出流中的第一个字符将替换为该流中被删除的最后一个字符.为什么会这样
- 正在将最后一个字符发送到std::cout
- 获取字符串流中的最后一个字符,而不复制其整个缓冲区
- remove_if字符串中的最后一个字符
- 如何删除最后一个字符
- 从字符数组中删除第一个和最后一个'X'字符
- C++文件中的最后一个字符
- (C++)如何从特定(结束)点查找 std::string 中的最后一个字符
- 如何获取您放入 ostream 对象中的最后一个字符