简体   繁体   English

C++中如何写入文件

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

I've tried to write to file in C++ on a mac in different ways and I can't.我试图以不同的方式在 Mac 上写入 C++ 中的文件,但我不能。 I've used:我用过:

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);

Can anyone help?谁能帮忙?

First thing you need to include fstream.首先你需要包含 fstream。 Second you declare the name of the file as an variable.其次,将文件名声明为变量。 You need to open it.你需要打开它。

#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;
}

If this dosen't work try to give the exact location of the file example如果这不起作用,请尝试给出文件示例的确切位置

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

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

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