2024/04/18

[C] chek cpu endian

1
2
3
4
5
6
7
8
#include <stdint.h>

static uint8_t is_little_endian(void)
{
    uint16_t value = 0x0001;
    uint8_t *byte_ptr = (uint8_t *)&value;
    return (*byte_ptr == 0x01); // If the system is little endian, the least significant byte is 0x01.
}


2024/04/09

[C] Create a folder even if the parent folder does not exist.

 

 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
static int my_dirname(char *path) {
    char *p = strrchr(path, '/');
    if (p == NULL || p == path) {
        return -1;
    }
    *p = '\0';
    return 0;
}

static int my_mkdir(char *path) {
    struct  stat    st;
    char            p[128];
    char            l[128];

    mkdir(path, 0775);
    while ((stat(path, &st) != 0)) {
        memset(p, 0, 128);
        memcpy(p, path, strlen(path));
        if (0 != my_dirname(p)) {
            return (-1);
        }
        while ((stat(p, &st) != 0)) {
            memset(l, 0, 128);
            memcpy(l, p, strlen(p));  // save the last not exist parent path.
            if (0 != my_dirname(p)) {
                return (-1);
            }
        }
        mkdir(l, 0775);
        if (stat(l, &st) != 0) {
            return (-1);
        }
        mkdir(path, 0775);
    }
    return (0);
}