【发布时间】:2020-08-25 06:36:42
【问题描述】:
我正在尝试学习如何将数据写入 C++ 中的文件,在本例中为 CSV 文件。目前我的代码将在我选择的位置创建文件,但是当我打开文件时,它是一个空白文档。这里的任何见解将不胜感激!谢谢。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const char *path = "/Users/eitangerson/desktop/Finance/ex2.csv";
ofstream file(path);
//string filename = "ex2.csv";
int main(int argc, const char * argv[]) {
file.open(path,ios::out | ios::app);
file <<"A ,"<<"B ,"<< "C"<<flush;
file<< "A,B,C\n";
file<<"1,2,3";
file << "1,2,3.456\n";
file.close();
return 0;
}
【问题讨论】:
-
你需要在关闭文件之前
file.flush()你的数据,因为它是临时写在内存中的,而不是在磁盘上 -
可能路径无效或者您没有在该位置写入的权限。
-
@AlexLarionov 它应该在关闭时自动刷新。
-
OT:避免使用全局变量。这不是一个好习惯。
-
这是一组有点奇怪的
openmode标志。试试ios::out | ios::trunc | ios::app。
标签: c++ c++17 fstream iostream