====================== Create a Wyrd Document ====================== Working with wyrd means working with documents of sorts - a collection of :doc:`properties <../properties>`. But before you can do that, you need to initialize the library. .. sourcecode:: c :linenos: :dedent: :caption: Initialize wyrd library #include wyrd_error_t err = WYRD_ERR_SUCCESS; struct wyrd_api * api = NULL; err = wyrd_create(&api); assert(WYRD_ERR_SUCCESS == err); assert(api != NULL); This call initializes global library context. You will need to provide this pointer to some other functions to inform them of this state. When you're done with your use of the library, you can safely dispose of this pointer again. .. sourcecode:: c :linenos: :dedent: :caption: Destroy wyrd API instance wyrd_destroy(&api); assert(api == NULL); With the API instance and a document file name, you can now go about creating your document file. Similar to `open(2)`_, we can pass flags to tell the function how to treat the file. In fact, most of the flags are modelled on those of the underlying system call. .. _`open(2)`: https://man7.org/linux/man-pages/man2/open.2.html .. sourcecode:: c :linenos: :dedent: :caption: Create document handle #include wyrd_error_t err = WYRD_ERR_SUCCESS; struct wyrd_handle * handle = NULL; err = wyrd_open_file(api, &handle, "testfile", WYRD_O_RW | WYRD_O_CREATE); assert(WYRD_ERR_SUCCESS == err); assert(handle != NULL); Similarly, to close a document handle, simply invoke the :c:func:`wyrd_close` function. .. sourcecode:: c :linenos: :dedent: :caption: Close document handle wyrd_close(&handle); assert(api == NULL); Now let's put all of this together into a possible main function for your program. .. sourcecode:: c :linenos: :dedent: :caption: Example main() with initialization and cleanup #include #include int main(int argc, char **argv) { wyrd_error_t err = WYRD_ERR_SUCCESS; struct wyrd_api * api = NULL; struct wyrd_handle * handle = NULL; int ret = 0; err = wyrd_create(&api); if (WYRD_ERR_SUCCESS != err) { fprintf(stderr, "Could not initialize wyrd: %s\n", wyrd_error_message(err)); ret = 1; goto cleanup; } err = wyrd_open_file(api, &handle, "testfile", WYRD_O_RW | WYRD_O_CREATE); if (WYRD_ERR_SUCCESS != err) { fprintf(stderr, "Could not create document: %s\n", wyrd_error_message(err)); ret = 2; goto cleanup; } // Dispatch to document processing process_document(handle); cleanup: wyrd_close(&handle); wyrd_destroy(&api); exit(ret); } And there you have it - a document created, ready to work with in the :doc:`next tutorial `.