'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. 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?
Solution 1:[1]
First thing you need to include 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");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Skerdi Velo |
