Developers Manual > Cocos2d-x > Modules > File IO > How to read and write file on different platforms

How to save/read file on different platforms

You can use standard c functions, such as fopen, fwrite, to save and read file on different platforms. Of cource, you can use other standard functions to operate with a file. The difficulty is the path to save or read a file.

This article modifies the “HelloWorld” example to show you how to save/read file on different platforms.

Now, CCFileUtils::getWriteablePath returns a writeable path. You can use it to get the writeable path.

1. Run example on different platforms

1.1 Android

  • Copy FileOperation.h and FileOperation.cpp into cocos2d-x/HelloWorld.
  • Invoke FileOperation::saveFile() and FileOperation::readFile() in HelloWorld::init().
  • Modify cocos2d-x/HelloWorld/android/jni/helloworld/Android.mk.
  • Rebuild and run

You will see the log in eclipse like:

Also, you can see the file content:

1.2 iOS

  • Copy FileOperation.h and FileOperation.mm into cocos2d-x/HelloWorld.
  • Invoke FileOperation::saveFile() and FileOperation::readFile() in HelloWorld::init().
  • Add FileOperation.h and FileOperation into project file.
  • Rebuild and run

You will see the log in eclipse like:

Also, you can see the file content:

Please reference to the apple document:
iOS Aplication Programming Guide - File & the File system
CHN version

1.3 Windows

  • Copy FileOperation.h and FileOperation.cpp into cocos2d-x/HelloWorld.
  • Invoke FileOperation::saveFile() and FileOperation::readFile() in HelloWorld::init().
  • Add FileOperation.h and FileOperation into project file.
  • Rebuild and run

You will see the log in eclipse like:

Also, you can see the file content:

2. Summary

This article just gives a guide of how to save/read file on different platforms. It is not the standard method,
just a workable method.

logIOS.jpg (74.5 kB) zhangxm, 2011-04-21 23:19

logWindows.jpg (84 kB) zhangxm, 2011-04-21 23:19

lsAndroid.jpg (21.4 kB) zhangxm, 2011-04-21 23:19

lsIOS.jpg (38.4 kB) zhangxm, 2011-04-21 23:19

addFileAndroid.jpg (17.1 kB) zhangxm, 2011-04-21 23:19

addFileIOS.jpg (23.9 kB) zhangxm, 2011-04-21 23:19

addFileWindows.jpg (28.7 kB) zhangxm, 2011-04-21 23:19

lsWindows.jpg (76 kB) zhangxm, 2011-04-21 23:19

logAndroid.jpg (115.8 kB) zhangxm, 2011-04-21 23:19

FileOperation.h (245 Bytes) zhangxm, 2011-04-22 00:10

FileOperation.cpp (1.5 kB) zhangxm, 2011-04-22 00:10

FileOperation.mm (1.1 kB) walzer@cocos2d-x.org, 2011-04-26 02:50

iosFileSave.png (71.6 kB) walzer@cocos2d-x.org, 2011-04-26 03:05

Sign up for our newsletter to keep up with the latest developments, releases and updates for Cocos2d-x.