how do i save to a file?

Hi, new to openframeworks. I’ve used processing quite a bit, and i’d like to know if there is a way to save variables to a txt file? Also, how would I be able to open said txt file… Any suggestions would be greatly apprecciated. tyvm.

see this XML example. i think that’s the easiest way to go.
http://wiki.openframeworks.cc/index.php?title=Using-XML

sample code in the addons folder.

boranj,
dan

ya… you can use the ofxXmlSettings addon if you wanna save it as XML… if you just want a plain ol flat txt file, check this link: C+±Input/Output-with-files

Examples:

  
  
// writes myVariable to file named filename  
ofstream fout(ofToDataPath(filename).c_str());  
fout << myVariable << endl;  
fout.close();  
  

  
  
// reads myVariable from file named filename  
int myVariable;  
ifstream fin(ofToDataPath(filename).c_str());  
if(fin.is_open()){  
	fin >> myVariable; // could be dangerous - assumes valid int is in filename  
	fin.close();  
}  
else  
	myVariable = -1;  
  

Notice in the reading example, we are reading a ifstream directly to an int. This could be dangerous if the file does not contain a valid int. Consider using the following function to validate and convert a string to a different type (this one is really useful and I find myself using it very often to safely convert from strings to other data types):

  
  
// converts a string to any type. Source: [http://www.codeguru.com/forum/showthread.php?t=231054](http://www.codeguru.com/forum/showthread.php?t=231054)  
template <class T>  
bool from_string(T& t, const std::string& s, std::ios_base& (*f)(std::ios_base&)){  
	if(s != ""){  
		std::istringstream iss(s);  
		return !(iss >> f >> t).fail();	  
	}  
};  
  

Putting it into play with our above file reading:

  
  
// reads myVariable from file named filename  
int myVariable;  
string cInput;  
ifstream fin(ofToDataPath(filename).c_str());  
if(fin.is_open()){  
	fin >> cInput;  
	fin.close();  
  
	// attempt to convert from string to int  
	if(from_string(myVariable, cInput, std::dec) == false)  
		myVariable = -1; // it failed, so take a default value  
}  
else{  
	myVariable = -1;  
}  
  

HTH!

-plong0