close()我使用时需要手动拨打电话std::ifstream吗?
例如,在代码中:
std::string readContentsOfFile(std::string fileName) {
std::ifstream file(fileName.c_str());
if (file.good()) {
std::stringstream buffer;
buffer << file.rdbuf();
file.close();
return buffer.str();
}
throw std::runtime_exception("file not found");
}
Run Code Online (Sandbox Code Playgroud)
我需要file.close()手动拨打电话吗?不应该ifstream使用RAII来关闭文件?
我认为这应该很简单,但到目前为止我的谷歌搜索没有帮助...我需要用C++写入现有文件,但不一定在文件的末尾.
我知道当我只想将文本附加到我的文件时,我可以ios:app在调用open我的流对象时传递该标志.但是,这只是让我写到文件的最后,而不是写到它的中间.
我做了一个简短的程序来说明这个问题:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
string path = "../test.csv";
fstream file;
file.open(path); // ios::in and ios::out by default
const int rows = 100;
for (int i = 0; i < rows; i++) {
file << i << "\n";
}
string line;
while (getline(file, line)) {
cout << "line: " << line << endl; // here I would like to append more text to certain rows
}
file.close(); …Run Code Online (Sandbox Code Playgroud) 在C++中,我需要写入现有文件并保留以前的内容.
这就是我所做的:
std::ofstream logging;
logging.open(FILENAME);
logging << "HELLO\n";
logging.close();
Run Code Online (Sandbox Code Playgroud)
但后来我的文字被覆盖了(不见了).我做错了什么?
提前致谢.
我创建了一个在 .txt 文件中编写代码并从中读取内容的代码。但是,如果我关闭程序并再次开始写入,它会删除旧文本并用新文本覆盖它。
有没有办法不覆盖现有数据?
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void check() {
string text;
ifstream file;
file.open("test.txt");
getline(file, text);
if (text == "") {
cout << "There's no data in file" << endl;
} else {
cout << "File contains:" << endl;
cout << text << endl;
}
}
int main() {
check();
string text;
ofstream file;
file.open("test.txt");
cout << "Type some text" << endl;
getline(cin, text);
file << text;
return 0;
}
Run Code Online (Sandbox Code Playgroud)