Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "sqlite3.h"
- #include <stdio.h>
- #include <stdlib.h>
- void execute_script(const char *database_path, const char *script_text);
- int parse_arguments(int argc, char**argv, char **database_path, char **script_path);
- char *read_file(const char *file_path);
- const char *const PARAM_HELP = {
- "The following parameters are accepted:\n"
- "\t/d [database path] /s [script path]\n"
- "\t/s [script path] /d [database path]"
- };
- int main(int argc, char **argv)
- {
- char *database_path, *script_path;
- if (parse_arguments(argc, argv, &database_path, &script_path))
- {
- char *script_text = read_file(script_path);
- if (script_text == NULL)
- {
- printf("unable to open file: %s\n", script_path);
- }
- else
- {
- execute_script(database_path, script_text);
- free(script_text);
- }
- }
- else
- {
- printf(PARAM_HELP);
- }
- }
- char *allocate_string(size_t string_length)
- {
- char *result = malloc(string_length + 1);
- if (result != NULL)
- {
- result[string_length] = '\0';
- }
- return result;
- }
- void execute_script(const char *database_path, const char *script_text)
- {
- sqlite3* database;
- const int error_code = sqlite3_open_v2(database_path, &database, SQLITE_OPEN_READWRITE, NULL);
- if (error_code)
- {
- printf("%s\n", sqlite3_errstr(error_code));
- }
- else
- {
- char *error_message = NULL;
- if (sqlite3_exec(database, script_text, NULL, NULL, &error_message))
- {
- printf("%s\n", error_message);
- sqlite3_free(error_message);
- }
- }
- sqlite3_close(database);
- }
- long file_length(FILE *file)
- {
- const long initial = ftell(file);
- fseek(file, 0, SEEK_END);
- const long length = ftell(file);
- fseek(file, initial, SEEK_SET);
- return length;
- }
- const size_t VALID_ARGC = 5;
- int parse_arguments(int argc, char**argv, char **database_path, char **script_path)
- {
- *database_path = *script_path = NULL;
- if (argc == VALID_ARGC)
- {
- for (size_t i = 1; i < VALID_ARGC; ++i)
- {
- if (argv[i][0] != '/' || !argv[i][1] || argv[i][2]) return 0;
- switch (argv[i][1])
- {
- case 'd':
- case 'D':
- *database_path = argv[++i];
- break;
- case 's':
- case 'S':
- *script_path = argv[++i];
- break;
- default:
- return 0;
- }
- }
- }
- return *database_path && *script_path;
- }
- const char *const FILE_OPEN_MODE = "rb";
- const size_t NUMBER_FILE_ELEMENTS = 1;
- char* read_file(const char *file_path)
- {
- char *text = NULL;
- FILE *file = fopen(file_path, FILE_OPEN_MODE);
- if (file)
- {
- const long file_size = file_length(file);
- if (file_size)
- {
- if ((text = allocate_string(file_size)))
- {
- if (fread(text, file_size, NUMBER_FILE_ELEMENTS, file) != NUMBER_FILE_ELEMENTS)
- {
- free(text);
- text = NULL;
- }
- }
- }
- fclose(file);
- }
- return text;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement