diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..7af3cbc --- /dev/null +++ b/examples/README.md @@ -0,0 +1,13 @@ +# Examples + +This project includes the following two examples: + +- [`print_hex.cpp`](./print_hex.cpp): + Prints the hexadecimal representation of the given number. + This code returns an error if the provided input is not a number. + This example demonstrates the basic flow of error handling and how to return an error object from a function. + +- [`read_file.cpp`](./read_file.cpp): + Reads a file from the given path and prints its content. + This code returns an error if it fails to open the file. + This example illustrates the same error handling flow but with examples of how to create an error object with a formatted message. \ No newline at end of file diff --git a/examples/print_hex.cpp b/examples/print_hex.cpp index 0564c1a..8026f0b 100644 --- a/examples/print_hex.cpp +++ b/examples/print_hex.cpp @@ -1,12 +1,15 @@ #include #include +// Prints the hexadecimal representation of the given number string. errors::Error print_hex(const char* number_str) { int number = std::atoi(number_str); - if (number == 0) { + if (number_str[0] != '0' && number == 0) { + // The given string is not a number, return an error. return errors::make("is not a number"); } + // Print the number and return nil. std::cout << std::hex << number << std::endl; return errors::nil(); } @@ -17,6 +20,7 @@ int main(int argc, char **argv) { return 1; } + // Call the function and handle the error. const auto err = print_hex(argv[1]); if (err) { std::cerr << err << std::endl; diff --git a/examples/read_file.cpp b/examples/read_file.cpp index d9b3351..5aeb185 100644 --- a/examples/read_file.cpp +++ b/examples/read_file.cpp @@ -2,17 +2,19 @@ #include #include +// Reads the file from the given path and prints the contents. errors::Error read_file(const char* filepath) { std::ifstream file(filepath); if (!file.is_open()) { - return errors::format("failed to open `{}` ({})", filepath, static_cast(file.rdstate())); + // Unable to open the file, return an error. + return errors::format("failed to open '{}' ({})", filepath, static_cast(file.rdstate())); } + // Print the file contents and return nil. std::string line; while (std::getline(file, line)) { fmt::print("{}\n", line); } - return errors::nil(); } @@ -22,6 +24,7 @@ int main(int argc, char **argv) { return 1; } + // Call the function and handle the error. const auto err = read_file(argv[1]); if (err) { fmt::print(stderr, "{}\n", err);