Search code examples
c++visual-studio-2010fstreamdocuments

C++ Save a text document


I've been working on my game and I can easily save my text document, everything works perfectly. My question is, how can I save the text document into a file called "Saves." Here is my code.

Also! I get the input for the char* name from

Save(gets(new char [50]));

Why won't this code work right here?

char* newArray = new char[strlen("PaintAPicture/")+strlen("Saves/")+strlen(name)+strlen(".asciip")+1];
        strcpy(newArray,"PaintAPicture/");
        strcpy(newArray,"Saves/");
        strcpy(newArray,name);
        strcat(newArray,".asciip");

I took what you said about using a string, but it's not creating the file and I get the Saving Failed, Main Problem error.

if(saveFile)
    {
        system("cls");
        string prename;
        cout << "Enter level's number: ";
        cin >> prename;
        string name = "Files/" + "Saves/" + prename + ".asciip";

        ofstream out(name, ios::binary);
        if (!out.is_open()){ MessageBox( 0, "Saving failed! Main problem.", 0, MB_ICONERROR); system("cls"); RedrawMap(); return 0; }

        system("cls"); cout << "Saving...";


        system("cls");
        ShowConsoleCursor(false);
        cout << "Saving...";
        Sleep(1000);

        for(int i = 9; i < SizeY; i++)
        {
            for(int j = -1; j < SizeX; j++)
            {
                out << Map[i][j].ch << endl;
                out << (int)Map[i][j].color << endl;
            }
        }
    }

    cout << '\a';
    out.close();
}

Solution

  • Prepend the filename with "Saves/"

    char* newArray = new char[strlen("Saves/")+strlen(name)+strlen(".asciip")+1];
    strcpy(newArray,"Saves/");
    strcat(newArray,name);
    strcat(newArray,".asciip");
    

    Also std::string class is designed for storing and manipulating strings. Much easier to use and a lot less error prone than C-strings. Info on string.

    EDIT: Your first piece of code

    char* newArray = new char[strlen("PaintAPicture/")+strlen("Saves/")+strlen(name)+strlen(".asciip")+1];
        strcpy(newArray,"PaintAPicture/");
        strcpy(newArray,"Saves/");
        strcpy(newArray,name);
        strcat(newArray,".asciip");
    

    doesn't work becouse you're using strcpy where you should use strcat.

    strcpy(newArray,"Saves/");
    strcpy(newArray,name);
    

    should be

    strcat(newArray,"Saves/");
    strcat(newArray,name);
    

    As for the problem with creating the file, do those folders exist already? ofstream can create new files to a specified folder, but it cannot create new folders. See https://stackoverflow.com/a/9089919/4761271