Throwing 'success' and optimising a fstream function

I've made a function that retrieves filenames from a binary archive. It's part of the "Archive" class.

The filenames are, or rather should be, null-terminated, can be no longer than 255 characters and (tbd) must be ASCII characters.

If there is no filename and a null is the first character read, it's assumed to be EOF and the archive has been successfully read.

All I'm looking to do now is how to handle errors, handle success (EOF), and how to improve the readability and performance of the function.

Probably painfully obvious to the experts, but just want to check I'm on the right tracking with throw exceptions for both errors and success, and that everything else is alright.

Here's the function so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
std::string Archive::getFilename() {
    std::string filename = "";
    uint8_t count = 0;
    // Something safer than while(true)?
    while (true) {
        if (count == 255) {
            std::cout << "Filename is too long" << std::endl;
            throw "Filename is too long";
        }

        int8_t character;
        if (!archive.read( (char*)&character, 1 )) {
            std::cout << "Error reading filename" << std::endl;
            throw "Error reading filename";
        }

        if (isprint(character)) {
            filename += character;
        } else if(character == '\0' && filename != "") {
            break;
        } else if(character == '\0') {
            std::cout << "End of file character detected" << std::endl;
            // Probably shouldn't throw an error here, but what instead?
            throw "End of file character detected"; // Success, eof reached
        } else {
            std::cout << "Invalid character in filename" << std::endl;
            throw "Invalid character in filename";
        }

        count++;
    }
    return filename;
}
Throwing exceptions makes so sense for successful operation. Exceptions are there to report problems.
Exceptions provide a way to react to exceptional circumstances (like runtime errors) in programs by transferring control to special functions called handlers.

http://www.cplusplus.com/doc/tutorial/exceptions/


Not throwing an exception can mean success - like so
1
2
3
4
5
6
7
8
9
try
{
   Archive::getFilename();
   cout << "Success"; // success when reaching here
}
catch (exception& ex)
{
   // handle error
}
reading 1 char at a time is a performance killer. So is testing for eof after each char.

If the file fits into ram, read it entirely and parse a memory buffer.
If the file is too big (and these days, that means over 10gb for even home systems, and 30-100+gb for commercial systems) read in large blocks (ideally, disk sector related sized blocks, but that is really going deep).

Last edited on
Topic archived. No new replies allowed.