Search code examples
c++fopen

Expection thrown on "fopen"


I wrote a function to read back a binary file. When doing the debug, it showed "exception Thrown" on line "pFile=fopen(filename, "rb");". I don't know why. Also, how to return readback buffer in the function "read_back(const char*filename)"

void read_back(const char *filename)
{
    FILE* pFile;
    long lSize=100;
    char* buffer;
    buffer = (char*)malloc(sizeof(char)*lSize);
    pFile = fopen(filename, "rb");
    if (pFile == NULL) { fputs("File error", stderr); exit(1); }

    // copy the file into the buffer:
    size_t result = fread(buffer, 1, lSize, pFile);
    if (result != lSize) { fputs("Reading error", stderr); exit(3); }
       fclose(pFile);   
}

int main() 
{
    const char *fname[2];
    fname[1] = "C:\\1_data.bin";
    fname[2] = "C:\\2_data.bin";
    fname[3] = "C:\\3_data.bin";

    for (int i = 0; i < 2; ++i) 
    {
        read_back(fname[i]);
    }
    return 0;
}

Solution

  • Several issues in your code.

    First of all an array index starts with 0. The fname is array of 2 char * and you have missed initializing the fname[0]. Moreover you are initializing the array past the end of the array - fname[2] and fname[3]. Since your program is suppose to read three files, you should do:

        const char *fname[3];
        fname[0] = "C:\\1_data.bin";
        fname[1] = "C:\\2_data.bin";
        fname[2] = "C:\\3_data.bin";
    

    Change the loop condition to i < 3.

    In the read_back(), you are setting lSize to 100 and below in the code you are doing

    if (result != lSize) { fputs("Reading error", stderr); exit(3); }
    

    That means, the file to be read should have number of bytes, read by fread(), either 100 or more otherwise it's a Reading error. Also, if the file is having more than 100 bytes then except the first 100 bytes it will be unread. May you should call fread() in a loop and read till the end of file.