如何在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");
我曾尝试以不同的方式在 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");