I keep getting coredumps when i run this function.

void readUser(int uid)  ///Reads users from data directory
{
    std::stringstream fileName;

    fileName << "./data/" << uid << ".dat";
    user myUser;
    std::cout << "USERNAME:" << myUser.name << "\n UID:" << myUser.uid;

    ///Reads data from file
    FILE* dat = fopen(fileName.str().c_str(),"rb");
    fread(&myUser, sizeof(user), 1, dat);
    fclose(dat);

    ///Copy collected data to bufferUser
    strncpy(myUser.name, bufferUser.name, 255);
    bufferUser.uid = myUser.uid;

}

Heres a link to the file in question.
https://github.com/JeroenMathon/ColdFusion/blob/Development/src/dataio.cpp

Fixed it by adding a File Checker.

FILE* dat = fopen(fileName.str().c_str(),"rb");
    if(!dat)
    {
        std::cout << "UID:No Data!\n";
        return;
    }

The only obvious thing that I can see that would cause a crash is at lines 10 and 11.
At line 10, you attempt to open and get a pointer to a file with the filename you have set-up. But you haven't performed any kind of check on the pointer before using it in the call to fread at line 11. So if the file pointer is invalid (because fopen failed to find or open the file), you're likely to experience a crash!

So you should check the state of the pointer before attempting to read the file:

///Reads data from file
if(FILE* dat = fopen(fileName.str().c_str(),"rb"))
{
    fread(&myUser, sizeof(user), 1, dat);
    fclose(dat);
    //.... rest of your code
}
else
{
    // Failed to open the file!
}

Also, why are you using C style FILE pointers instead of C++ streams?

EDIT: Ah, you self-solved while I was writing this! I was too slow!

Edited 2 Years Ago by JasonHippy

This question has already been answered. Start a new discussion instead.