0

Having gone through several different questions that were about roughly the same thing, I've just decided to make my own question. Every time my code is run it says exited with code -107371819 and I can't quite figure out what's wrong with it. I know that this code is usually thrown when the program attempts to read uninitialized memory, but I'm not sure where that's happening in my code.

I'm attempting to read through all of the structures of type/size Tool. It does successfully list all of them (not in the prettiest format) and successfully closes the file, however after this occurs the program throws that lovely read access error.

Here's the Tool structure:

struct Tool {
    int tid; // "Tool identification number"
    string name;
    int quantity;
    double cost;
};

This is the code that I've been attempting to run:

void listTools() {
    // Iterates through the whole file while printing each Tool struct
    fstream file;
    file.open("hardware.txt", ios::binary | ios::in);
    Tool temp = Tool();
    while (!file.eof()) {
        file.read((char*)&temp, sizeof(Tool)); // <-- I think this is my problem line
        if (file.fail()) {
            cout << "File failed to read, end of file has been reached." << endl;
            break;
        }
        cout << temp.getTid() << temp.getName() << temp.getQuantity() << temp.getCost() << endl; // Again, not pretty
    }
    file.clear();
    file.close();
    cout << "File closed successfully." << endl;
    // Access error happens here
}

The part that makes this a little weird is that it ran properly once, but I haven't changed anything from that point. Any help is appreciated!

BobdaFett
  • 1
  • 1
  • 1
    `while (!file.eof()) {` almost always results in an off-by-one error. Is the file actually binary, or is it plaintext? My guess is it's plaintext. – sweenish May 11 '22 at 18:43
  • You don't provide enough information, like a sample file. Please read about the [mre]. – sweenish May 11 '22 at 18:45
  • Looking a bit closer, there's no way that binary read is going to work. `std::string` is not trivially copyable. And if you're doing binary writes and reads, you'd be well served to use a sized integer type instead of regular `int`. – sweenish May 11 '22 at 18:48
  • Strings and text are variable length records. I recommend writing the length of the string to the file, followed by the actual text. This allows you to block write the text. When you read, reading the length first will allow you to allocate memory first for the string, then block read the text. – Thomas Matthews May 11 '22 at 19:55
  • Would swapping the string to a C-string work better? Specifically one with a specified size of... let's say 25 characters. – BobdaFett May 12 '22 at 00:26

0 Answers0