File IO solution

Hello I’ve been looking for a complete example about how to write/read to a file using standard C++ not C.
Can someone please show me a working example of how to do this in cocos2d-x?

Reading:
String: auto myString = FileUtils::getInstance()->getStringFromFile("AFile.txt");
ValueMap: auto myValueMap = FileUtils::getInstance()->getValueMapFromFile("MyValueMap.plist");
ValueVector: auto myValueVector = FileUtils::getInstance()->getValueVectorFromFile("MyValueVector.plist");
Binary Data: auto myData = FileUtils::getInstance()->getDataFromFile("MyData.dat");

Writing:
You should write data to the writeable folder.
Writable path: auto path = FileUtils::getInstance()->getWritablePath();

String: FileUtils::getInstance()->writeStringToFile("My String Text", path + "AFile.txt");
ValueMap: FileUtils::getInstance()->writeValueMapToFile(myValueMap, path + "MyValueMap.plist");
ValueVector: FileUtils::getInstance()->writeValueVectorToFile(myValueVector, path + "MyValueVector.plist");
Binary Data: FileUtils::getInstance()->writeDataToFile(myData, path + "MyData.dat");

Hope that helps.

Is it ok to use std::streams?

Not sure sorry. I’d recommend sticking to cocos’s functions unless you need to do something that cocos doesn’t support. If you did use something outside of cocos, you’d probably have to check for compatibility on each platform you were developing for. I’m sure using features of the std library should be fine though.

Alright thanx for you help I will use std but if it goes wrong on the platforms that I’m building for I will change to cocos2d-x standards :slight_smile: thank you!

@sheshmoshen use what works best for you and is easiest for you to understand. I agree with grimfate because the cross-platform feature of the engine is taken seriously with most features not allowed into the engine if it doesn’t support all platforms.

That said, if std::/STL streams or other works fine for you on your target platforms there’s no reason you can’t use them. You could always use stringstream, for example, and then use only the read/write string functionality from cocos2d.

good luck!

I did run into problems on some devices i will have to rewrite everything:

Also how about using c function i.e FILE struct is that ok for cocos2d-x?

Yes, you can. I believe the Android (and probably linux) is using the POSIX file ‘C’ APIs

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.