#include <fcntl.h>
#include <liburing.h>
#include <stdio.h>
#include <unistd.h>

struct io_uring ring;

int main(int argc,  char * argv[]) {
      if(argc != 2) {
            printf("usage:   %s FILE - prints file to console.\n", argv[0]);
            return 1;
      }

      int fd = open(argv[1], 0);
      if(fd < 0) {
            printf("Could not open file %s.\n", argv[1]);
            return 2;
      }

      /* prep the array */
      char data[512];
      struct iovec iov = { data, 512 };

      /* init liburing */
      io_uring_queue_init(256, &ring, 0);

      /* declare required structs */
      struct io_uring_sqe * sqe;
      struct io_uring_cqe * cqe;

      /* get an sqe and fill in a READV operation */
      sqe = io_uring_get_sqe(&ring);
      io_uring_prep_readv(sqe, fd, &iov, 1, 0);

      sqe->user_data = data;

      /* tell the kernel we have an sqe ready for consumption */
      io_uring_submit(&ring);

      /* wait for the sqe to complete */
      int ret = io_uring_wait_cqe(&ring, &cqe);
      
      /* read and process cqe event */
      if(ret == 0) {
            char * out = cqe->user_data;
            signed int len = cqe->res;
            io_uring_cqe_seen(&ring, cqe);

            if(len > 0) {
                  printf("%.*s", len, out);
            }
      }
      else {
            printf("%d\n", ret);
            io_uring_cqe_seen(&ring, cqe);
      }

      io_uring_queue_exit(&ring);

      close(fd);
}