-3

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;
}
user10293779
  • 103
  • 6
  • 1
    `fname[2] = "C:\\2_data.bin";` and `fname[3] = "C:\\3_data.bin";` are both out of bounds. – drescherjm Jan 21 '19 at 14:35
  • 1
    You have an array `fname` of ***two*** elements. Then you assign to elements ***two to four*** in that array. That won't work very well. – Some programmer dude Jan 21 '19 at 14:35
  • 1
    Since you declare it as `const char *fname[2];`, there are only two fields: `fname[0]` and `fname[1]` . Yet you try to access `fname[2]` and `fname[3]`. – Blaze Jan 21 '19 at 14:35
  • 5
    And if you really want to learn C++, then please stop using the C functions and learn C++ properly. I suggest getting a couple of books from [this curated list](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) to read. – Some programmer dude Jan 21 '19 at 14:36
  • 1
    You also pass fname[0] to your function, but you never initialize fname[0]. – stefaanv Jan 21 '19 at 14:41

1 Answers1

2

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.

H.S.
  • 11,654
  • 2
  • 15
  • 32