|
| 1 | +#include <fcntl.h> |
| 2 | +#include <stdbool.h> |
| 3 | +#include <stdio.h> |
| 4 | +#include <stdlib.h> |
| 5 | +#include <string.h> |
| 6 | + |
| 7 | +struct Connection_t { |
| 8 | + int file_descriptor; |
| 9 | +}; |
| 10 | +typedef struct Connection_t Connection; |
| 11 | + |
| 12 | +Connection* open_connection(char* filename) { |
| 13 | + int fd = open(filename, |
| 14 | + O_RDWR | // Read/Write mode |
| 15 | + O_CREAT, // Create file if it does not exist |
| 16 | + S_IWUSR | // Create file with user write permission |
| 17 | + S_IRUSR // Create file with user read permission |
| 18 | + ); |
| 19 | + |
| 20 | + if (fd == -1) { |
| 21 | + printf("Unable to open file '%s'\n", filename); |
| 22 | + exit(EXIT_FAILURE); |
| 23 | + } |
| 24 | + |
| 25 | + Connection* connection = malloc(sizeof(Connection)); |
| 26 | + connection->file_descriptor = fd; |
| 27 | + |
| 28 | + return connection; |
| 29 | +} |
| 30 | + |
| 31 | +char* get_db_filename(int argc, char* argv[]) { |
| 32 | + if (argc < 2) { |
| 33 | + printf("Must supply a filename for the database.\n"); |
| 34 | + exit(EXIT_FAILURE); |
| 35 | + } |
| 36 | + return argv[1]; |
| 37 | +} |
| 38 | + |
| 39 | +struct InputBuffer_t { |
| 40 | + char* buffer; |
| 41 | + size_t buffer_length; |
| 42 | + ssize_t input_length; |
| 43 | +}; |
| 44 | +typedef struct InputBuffer_t InputBuffer; |
| 45 | + |
| 46 | +InputBuffer* new_input_buffer() { |
| 47 | + InputBuffer* input_buffer = malloc(sizeof(InputBuffer)); |
| 48 | + input_buffer->buffer = NULL; |
| 49 | + input_buffer->buffer_length = 0; |
| 50 | + input_buffer->input_length = 0; |
| 51 | + |
| 52 | + return input_buffer; |
| 53 | +} |
| 54 | + |
| 55 | +void print_prompt() { printf("db > "); } |
| 56 | + |
| 57 | +void read_input(InputBuffer* input_buffer) { |
| 58 | + ssize_t bytes_read = |
| 59 | + getline(&(input_buffer->buffer), &(input_buffer->buffer_length), stdin); |
| 60 | + |
| 61 | + if (bytes_read <= 0) { |
| 62 | + printf("Error reading input\n"); |
| 63 | + exit(EXIT_FAILURE); |
| 64 | + } |
| 65 | + |
| 66 | + // Ignore trailing newline |
| 67 | + input_buffer->input_length = bytes_read - 1; |
| 68 | + input_buffer->buffer[bytes_read - 1] = 0; |
| 69 | +} |
| 70 | + |
| 71 | +int main(int argc, char* argv[]) { |
| 72 | + char* db_filename = get_db_filename(argc, argv); |
| 73 | + Connection* connection = open_connection(db_filename); |
| 74 | + |
| 75 | + InputBuffer* input_buffer = new_input_buffer(); |
| 76 | + while (true) { |
| 77 | + print_prompt(); |
| 78 | + read_input(input_buffer); |
| 79 | + |
| 80 | + if (strcmp(input_buffer->buffer, ".exit") == 0) { |
| 81 | + exit(EXIT_SUCCESS); |
| 82 | + } else { |
| 83 | + printf("Unrecognized command '%s'.\n", input_buffer->buffer); |
| 84 | + } |
| 85 | + } |
| 86 | +} |
0 commit comments