相关疑难解决方法(0)

我需要手动关闭ifstream吗?

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++ raii ifstream

187
推荐指数
5
解决办法
6万
查看次数

如何用C++写入文件的中间?

我认为这应该很简单,但到目前为止我的谷歌搜索没有帮助...我需要用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++ fstream ifstream ofstream

8
推荐指数
2
解决办法
9956
查看次数

C++:写入现有文件?

在C++中,我需要写入现有文件并保留以前的内容.

这就是我所做的:

std::ofstream logging;

logging.open(FILENAME);

logging << "HELLO\n";

logging.close();
Run Code Online (Sandbox Code Playgroud)

但后来我的文字被覆盖了(不见了).我做错了什么?

提前致谢.

c++

5
推荐指数
1
解决办法
2万
查看次数

如何在C++中保存.txt文件?

我创建了一个在 .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)

c++ visual-c++

2
推荐指数
1
解决办法
4万
查看次数

标签 统计

c++ ×4

ifstream ×2

fstream ×1

ofstream ×1

raii ×1

visual-c++ ×1