Search code examples
iphonexcodeipadifstreamofstream

XCode 7 - fstream does not work in iPhone simulator


the below shown functions are working well in Xcode, as long as I use them in OSX-applications... now I wrote an iOS-application where I would like to save some data in .txt files and read them again, but it does not work... there are neither files written, nor read... I already searched the net for solutions but I only found solutions to whenever it does not work in the OSX application (wrong directory, etc...) but that is not my case, there I already got it working...

what is the difference when I use it in the iOS simulator and how to get it running there?

//the below code is now the corrected version (before it was posted without the "this was missing" part.

void SaveData(std::string FileName)
{
    //!!this was missing
        char *H = getenv("HOME");
        std::string Home(H);
        std::string FileName = Home + "/Documents/" + FileName;

    std::ofstream FileOut (FileName);

    if (FileOut.is_open())
    {
        //!!write data to file
        FileOut.close();
    }
}


void LoadData(std::string FileName)
{
    //!!this was missing
        char *H = getenv("HOME");
        std::string Home(H);
        std::string FileName = Home + "/Documents/" + FileName;

    std::ifstream FileIn;
    FileIn.open(FileName.c_str(), std::ios::in);

    if(not FileIn.good())
    {
        //!!error message
        return;
    }

    //!!read data from file
    FileIn.close();
}

Solution

  • iOS is Sandboxed and restricts the area that can be read and written to and users/me/documents/xcodeprojects is incorrect.

    See About the iOS File System for details.

    There are several directories you can write and the Documents directory is probably what you want. You have to make a call to get the path, here are example calls in C++, Objective-C and Swift:

    C++ (Thx: Moritz Buchty):

    char *H = getenv("HOME");
    std::string Home(H);
    std::string FileName = Home + "/Documents/" + FileName;
    

    ObjC:

    NSArray *documentDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    

    Swift:

    let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String