qments/examples/print_info.c

92 lines
2.5 KiB
C
Raw Permalink Normal View History

/* Simple utility to get human-readable comment data */
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "comment.h"
#include "driver.h"
#include "drivers/unix_fs/unix_fs_driver.h"
#define BUF_SZ 4096
void
usage()
{
fprintf(stderr, "Simple utility to get comment info\n");
fprintf(stderr, "usage: <tool-name> [-p path] id\n");
fprintf(stderr, "-p path: path to comment storage \n");
fprintf(stderr, "id : id of comment \n");
}
int
main(int argc, char *argv[])
{
const Driver *driver = &unix_fs_driver;
char *path = ".";
int id, opt;
while ((opt = getopt(argc, argv, "p:")) != -1) {
switch (opt) {
case 'p':
path = optarg;
break;
default:
usage();
exit(EXIT_FAILURE);
}
}
if (optind >= argc) {
usage();
exit(EXIT_FAILURE);
}
id = atoi(argv[optind]);
if (id <= 0) {
usage();
exit(EXIT_FAILURE);
}
UnixFsDriverData driver_data = { path };
int max_id = unix_fs_driver_get_max_id(&driver_data);
if (max_id <= 0) {
fprintf(stderr, "Warning: failed to get id of last comment\n");
} else if (id >= max_id) {
fprintf(stderr, "Last comment has id %d, which is less than %d\n", max_id - 1, id);
exit(EXIT_FAILURE);
}
CommentHeader *header = malloc(sizeof(CommentHeader));
header->user_sid = malloc(BUF_SZ);
header->user_displayname = malloc(BUF_SZ);
if (driver->get_header(&driver_data, header, id) < 0) {
fprintf(stderr, "failed to get header of comment, are you sure it exists?\n");
exit(EXIT_FAILURE);
}
printf("Got a valid comment header\n");
printf("%-30s: %d\n", "Reply id", header->reply_id);
struct tm tm = *localtime(&header->creation_time);
printf("%-30s: %d-%02d-%02d %02d:%02d:%02d\n", "Creation time", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
printf("%-30s: %lu\n", "Text size in bytes", header->text_length);
printf("%-30s: %s\n", "User string ID", header->user_sid);
printf("%-30s: %s\n", "User displayname", header->user_displayname);
char *text_buffer = malloc(header->text_length + 1);
if (driver->get_text(&driver_data, text_buffer, id) < 0) {
fprintf(stderr, "failed to get text of comment\n");
exit(EXIT_FAILURE);
}
printf("Comment text:\n");
printf(text_buffer);
}