繁体   English   中英

C++中如何写入文件

[英]How to write to file in C++

我试图以不同的方式在 Mac 上写入 C++ 中的文件,但我不能。 我用过:

int bestScore = 3;
QFile data("bestScore.txt");
data.open(QIODevice::WriteOnly);
QTextStream out(&data);
out << bestScore;
data.close();
int bestScore = 3;
FILE *out_file = fopen("bestScore.txt", "w");
if (out_file == NULL) 
{   
  qDebug() << "File not open";
}
fprintf(out_file, "%d", bestScore);

谁能帮忙?

首先你需要包含 fstream。 其次,将文件名声明为变量。 你需要打开它。

#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}

如果这不起作用,请尝试给出文件示例的确切位置

myfile.open ("/Library/Application/randomfilename/example.txt");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM