Pergunta

I know there are a lot of questions similar to this, but I don't know of any that are the same, so here's my issue:

I'm trying to pass a filename as a const char * to my ifstream to read and load.

BUT: When I pass the filename, instead of reading the whole string "map.obj"; it just reads the first character "m" and as a result, the ifstream fails.

I don't know what I'm doing wrong and would appreciate a little help. My code follows:

#include <fstream>
using namespace std;

void loadModel(const char* filename);

int main()
{
    // Creates and positions the four boxes on the screen. Temporary.
    //rotation r = {0.0f, 0.0f, 0.0f};
    const char* filename = "map.obj";
    loadModel(filename);
    return 0;
    /*meshMgr.addObject(new Object());

    position p = {0.f, 10.f, 10.f};
    meshMgr.addObject(new Object(p, r));

    p.y = 0.f;
    p.z = 20.f;
    meshMgr.addObject(new Object(p, r));

    p.y = -10.f;
    p.z = 10.f;
    meshMgr.addObject(new Object(p, r));*/
}

void loadModel(const char* filename)
{
    ifstream in(filename, ios::in); //Open the model file
    if (in.is_open())   //if not opened, exit with -1
    {
        //Set up an array to act as a buffer for text read from the input file
        char buf[256];

        //Read input file text to end of file and push onto lines list
        while (!in.eof())
        {
            in.getline(buf, 256);
            //lines.push_back(new std::string(buf));
        }

        in.close();
    }
}

EDIT: Before anyone asks, yes the file is being referenced as a local file (do I need to use absolute paths or something?) and exists in the same directory as the source code

Foi útil?

Solução

As a response to my own question, it appears that my code didn't like passing the variable that stored the filename as a cost char * when the data in the variable was stored in a string-like format.

To counteract this, I simply changed the code from:

int main ()
{
...
const char* filename = "map.obj";
loadModel(filename);
...
return 0;
}

void loadModel(const char* filename)
{
...
}

to the following:

int main ()
{
...
string filename = "map.obj";
loadModel(filename);
...
return 0;
}

void loadModel(string filename)
{
...
}

where "..." indicates more code as shown in the question.

Outras dicas

This answers the error in the question, but begins with a string instead and uses a char instead of const char*. It's an alternative solution.

const char* not passing full filename

std::string filename = "map.obj";
char *cstr = new char[filename.length() + 1];
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top