Home > Enterprise >  How to write to file in C
How to write to file in C

Time:04-20

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?

CodePudding user response:

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");
  • Related