Using ofstream with MAX's save file dialogue...

Wes Jackson's icon

I want to use MAX's write file dialogue with ofstream to allow new lines to be written without storing them in an array, as I am trying to store more data than can be fit in an array!

Files are created by the dialogue, but is_open() remains false. I think the problem is that open() is not getting the correct path from the MAX dialogue. I include fstream and iostream.

Please let me know how to solve this problem! Thank you!

This is the function giving me errors:

'void myobject_writefile(t_myobject *x, char *filename, short path)
{
    t_filehandle fh;

    char cpath[1024]; // store intended filepath here

    // create the file
    long err = path_createsysfile(filename, path, 'TEXT', &fh);

    // get the full filepath in characters for ofstream, in the format: path/filename
    if (!(err = path_topotentialname(path, "", cpath, false))) {
        strcat(cpath, "/");
        strcat(cpath, filename);
        object_post((t_object *)x, "Writing %s", cpath);
    }
    else
        object_error((t_object *)x, "Error trying to create %ld", err);

    // open the file & write data
    ofstream out;
    out.open(cpath, fstream::out | fstream::app);

    if (out.is_open()) {
        out.open(cpath);

        out << "1 " << a << endl;
        out << "2 " << b << endl;
        out << "3 " << c << endl;
        out << "4 " << d << endl;

        out.close();

        sysfile_close(fh);
    }
    else
        object_error((t_object *)x, "Error trying to write to this file...");
}'

Timothy Place's icon

The problem is that the path returned by the Max API function is a Max-formatted path, not a POSIX path as expected by the file streams.

In Jamoma there is an example that uses libxml, which also requires POSIX paths, that you could use as an example. For example, the method hub_preset_doread():
https://github.com/jamoma/JamomaModular/blob/master/implementations/MaxMSP/jcom.hub/jcom.hub.presets.cpp#L710

In this method there is a call to a function called jcom_core_getfilepath() which does the conversion. That function is defined here:
https://github.com/jamoma/JamomaModular/blob/master/library/source/jcom.core.cpp#L190

HTH,
Tim