utils.c 1.6 KB
Newer Older
N
nocjj 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
/******************************************************************************
 * Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
 * vmtop licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v2 for more details.
 * Description: utils function
 ********************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
#include <time.h>
#include "utils.h"

int read_file(char *buf, int bufsize, const char *path)
{
    int fd;
    int len;
    char mpath[PATH_MAX];

    if (strlen(path) > PATH_MAX - 1 || realpath(path, mpath) == NULL) {
        return -1;
    }
    fd = open(mpath, O_RDONLY, 0);
    if (fd == -1) {
        return -1;
    }
    len = read(fd, buf, bufsize - 1);
    if (len > 0) {
        buf[len] = '\0';
    }
    close(fd);
N
nocjj 已提交
41
    return len;
N
nocjj 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
}

int get_time_str(char *buf, int bufsize)
{
    struct tm *tm_ptr;
    time_t now;

    time(&now);
    tm_ptr = localtime(&now);
    if (tm_ptr == NULL) {
        return -1;
    }
    if (strftime(buf, bufsize, "%Y-%m-%d %H:%M:%S", tm_ptr) == 0) {
        return -1;
    }
    return 1;
}