log.c

/*
 * File Name:     log.c
 * Author:        Jade Cheng
 * Date:          March 29, 2009
 * Course:        ICS 451
 * Assignment:    Project 2
 */

#include "common.h"
#include "log.h"

static void print_header(void);

/** The path to the log file. */
static char g_path[1000];

/** The pointer to the log file or standard output. */
static FILE * g_file;

/* ------------------------------------------------------------------------ */
extern void log_close(FILE * f)
{
    /* Close the log file. */
    assert(g_file != NULL);
    fclose(g_file);
    g_file = NULL;
}

/* ------------------------------------------------------------------------ */
extern void log_init(void)
{
    char   src[1000];
    FILE * f;
    size_t len;

    /* The log file path is stored in ~/.p2p/logfile.  Try to open this
     * file.  Replace the ~ with the path to the home directory. */
    sprintf(src, "%s/.p2p/logfile", getenv("HOME"));
    f = fopen(src, "r");
    if (f == NULL) {
        printf("Log setting not found in '%s'.\n", src);
        return;
    }

    /* The path is the first line of text in this file. */
    fgets(g_path, sizeof(g_path), f);
    fclose(f);

    /* Get rid of the \n at the end of the file. */
    len = strlen(g_path);
    if (len > 0 && g_path[len - 1] == '\n')
        g_path[len - 1] = '\0';

    /* Check if the log file is available. */
    f = fopen(g_path, "a");
    if (f == NULL) {
        printf("Log file '%s' not available.\n", g_path);
        return;
    }

    printf("Logging to '%s'...\n", g_path);
    fclose(f);
}

/* ------------------------------------------------------------------------ */
extern FILE * log_open(void)
{
    assert(g_file == NULL);

    /* Do not log anything if no log file is specified. */
    if (g_path[0] == '\0')
        return NULL;

    /* Do not log anything if the log file is not available. */
    g_file = fopen(g_path, "a");
    if (g_file == NULL)
        return NULL;

    /* Print a standard header and return the file pointer. */
    print_header();
    return g_file;
}

/* ------------------------------------------------------------------------ */
/**
 * Prints a header to the log file.
 */
static void print_header(void)
{
    time_t t;

    fprintf(g_file, "\n");

    /* Print the process id and the time each time the log is opened. */
    if (time(&t) != -1)
        fprintf(
            g_file,
            "p2p (pid = %d) at %s",
            (int)getpid(),
            asctime(localtime(&t)));

    fprintf(g_file,
        "----------------------------------------"
        "---------------------------------------\n");
}
Valid HTML 4.01 Valid CSS