ofFile cannot write to file

#1

For some reason I’m unable to write to file using ofFile(). of_v0.10.1_vs2017_release. See example below, what am I doing wrong?

#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){
	string data = "TEST!";
	ofFile userDataFile(ofToDataPath("userData.json"));
	userDataFile.create();
	if (!userDataFile.canWrite()) ofLogNotice("setup") << "Cannot write to userData.json!" << endl;
	userDataFile << data;
	userDataFile.close();
	ofLogNotice("setup") << "Just finished writing to and closing userData.json." << endl;
}

The file gets created but is empty (0kb size).

#2

Hmm. I don’t know. That also creates an empty file for me. I also tried using put() and sync() (in case there is a timing issue) and setWriteable() and still got no data.

I don’t see any useful examples of saving to a file in the OF examples.

What I do is put my data in a string and then do this to save it:

// Put it in an ofBuffer, and stuff the Buffer into a file:
ofBuffer aBuffer(sData.c_str(), sData.size());
return ofBufferToFile(toPath, aBuffer, false);

Which seems to work nicely, but may not suit your needs.

1 Like