Linux C语言常用代码

1、读取文件全部内容

#include <stdio.h>
#include <stdlib.h>
 
int main(int argc, char* argv[])
{
    char ch;
    FILE* fp;
    unsigned long int count = 0;
    char buf[1025] = {0};
 
    // 这里要求我们在输入两个参数,第一个为 exe 路径,第二个为 文件名
    // 如 file_test.exe test.txt
    if (argc != 2)
    {
        printf("Usage: %s filename\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    if ((fp = fopen(argv[1], "r")) == NULL)
    {
        // 如果文件打开失败(通常是文件不存在),则结束程序
        printf("Can't open %s\n", argv[1]);
        exit(EXIT_FAILURE);
    }
    while ((ch = getc(fp)) != EOF && count < 1024)
    {
        // 显示文本内容并计数
        buf[count] = ch;
        count++;
    }
    fclose(fp);
    printf("%s\n", buf);
    printf("File %s has %lu characters\n", argv[1], count);
 
    return 0;
}

2、cJSON解析字符串

编译选项要加 -lm

示例源串

{
	"server": {
		"nodes": [{
			"ip": "10.76.76.190",
			"port": 6379
		}, {
			"ip": "10.76.76.191",
			"port": 6380
		}, {
			"ip": "10.76.76.192",
			"port": 6381
		}],
		"password": "admin"
	},
	"isssl": true
}

示例代码(每一行记得判空,编译时加-lm选项)

#include <stdio.h>
#include "cJSON.h"
int main(){

    char c[] = "{\"server\":{\"nodes\":[{\"ip\":\"10.76.76.190\",\"port\":6379},{\"ip\":\"10.76.76.191\",\"port\":6380},{\"ip\":\"10.76.76.192\",\"port\":6381}],\"password\":\"admin\"},\"isssl\":true}";

    cJSON* root = cJSON_Parse(c);
    cJSON* json_server = cJSON_GetObjectItem(root, "server");
    cJSON* json_isssl = cJSON_GetObjectItem(root, "isssl");
    cJSON* json_password = cJSON_GetObjectItem(json_server, "password");
    cJSON* json_nodes = cJSON_GetObjectItem(json_server, "nodes");

    int i = 0;
    for (; i != cJSON_GetArraySize(json_nodes); ++i) {
        cJSON* each = cJSON_GetArrayItem(json_nodes, i);
        cJSON* json_ip = cJSON_GetObjectItem(each, "ip");
        cJSON* json_port = cJSON_GetObjectItem(each, "port");
        printf("ip %s\n", json_ip->valuestring);
        printf("port %d\n", json_port->valueint);
    }

    printf("password %s\n", json_password->valuestring);
    printf("is ssl %s\n", json_isssl->valueint ? "true":"false");
    cJSON_Delete(root);
}

3、curl拿到回传的数据

编译选项要加  -lcurl

头部选项参考

https://curl.se/libcurl/c/curl_easy_setopt.html

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>

struct string {
    char* ptr;
    size_t len;
};

void init_string(struct string* s) {
    s->len = 0;
    s->ptr = malloc(s->len + 1);
    if (s->ptr == NULL) {
        fprintf(stderr, "malloc() failed\n");
        exit(EXIT_FAILURE);
    }
    s->ptr[0] = '\0';
}

size_t writefunc(void* ptr, size_t size, size_t nmemb, struct string* s) {
    size_t new_len = s->len + size * nmemb;
    s->ptr = realloc(s->ptr, new_len + 1);
    if (s->ptr == NULL) {
        fprintf(stderr, "realloc() failed\n");
        exit(EXIT_FAILURE);
    }
    memcpy(s->ptr + s->len, ptr, size * nmemb);
    s->ptr[new_len] = '\0';
    s->len = new_len;

    return size * nmemb;
}

int main(void) {
    CURL* curl;
    CURLcode res;

    curl = curl_easy_init();
    if(curl) {
        struct string s;
        init_string(&s);

        curl_easy_setopt(curl, CURLOPT_URL, "https://www.baidu.com");
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "test");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
        res = curl_easy_perform(curl);

        printf("打印数据:\n%s", s.ptr);
        free(s.ptr);

        /* always cleanup */
        curl_easy_cleanup(curl);
    }
    return 0;
}

4、获取随机数

#include <stdio.h>

int main(int argc, char* argv[]){

    srand((int)time(0));

    //打印 32位 test 随机数,并用16进制表示
    int test2 = rand();
    printf("%lx   \n", test2);

    // 打印 64位 test 随机数,并用16进制表示, 016代表不足16位的部分,补零,llx代表打印64位的16进制数
    unsigned long long test = ((unsigned long long)rand() << 32) + rand();
    printf("%016llx   \n", test);

    return 0;
}

5、定义按位的结构体

总结,按照位定义结构体,一定要都按照位定义,不然会出现意想不到的错误,而且一定要定义无符号的

#include <stdio.h>
#pragma pack (1)

struct test1 {

    unsigned char cloud_id:3;
    unsigned char vendor_id:4;
    unsigned short machine_id;
    unsigned long long current_time:41;

};

struct test2 {

    unsigned char cloud_id:3;
    unsigned char vendor_id:4;
    unsigned short machine_id:16;
    unsigned long long current_time:41;

};


int main(int argc, char* argv[]){

    printf("test1 大小 : %d \n", sizeof(struct test1));
    printf("test2 大小 : %d \n", sizeof(struct test2));

    return 0;
}

6、按位打印01字节码

#include <stdio.h>
// 修改type后面的类型,可以查看各种数的字节码
#define type unsigned int

void print_bin(type num)
{
    int len = sizeof(type);
    int n = 8;
    int i, j, k;
    unsigned char *p = (unsigned char*)&num + len -1;

    for (i = 0; i < len; i++) //处理len个字节
    {
        j = *(p - i); //取每个字节的首地址
        for ( k = 7; k >= 0; k--) //处理每个字节的8个位
        {
            if (j & (1 << k))
                printf("1");
            else
                printf("0");
        }
        printf(" ");
    }
    printf("\r\n");
}


int main(int argc, char* argv[]){

    type a = 100;
    print_bin(a);

    return 0;
}

7、打印16进制字节码

#include<stdio.h>
typedef unsigned char uint8;
#define HEXDUMP_LINE_LENGTH 16
void hex_dump(uint8* data, int length)
{
    uint8* p = data;
    int i, line, offset = 0;

    while (offset < length)
    {
        printf("%04x ", offset);

        line = length - offset;

        if (line > HEXDUMP_LINE_LENGTH)
            line = HEXDUMP_LINE_LENGTH;

        for (i = 0; i < line; i++)
            printf("%02x ", p[i]);

        for (; i < HEXDUMP_LINE_LENGTH; i++)
            printf("   ");

        for (i = 0; i < line; i++)
            printf("%c", (p[i] >= 0x20 && p[i] < 0x7F) ? p[i] : '.');

        printf("\n");

        offset += line;
        p += line;
    }
}

8、打印字节码简易版

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main() {
    unsigned char Buf[] = "123456";
    unsigned int len = strlen(Buf);
    char* Buf1 = (char*)malloc(len * 3 + 1);
    int i = 0, k = 0;
    for (; i < len * 3; i += 3, k++)
        snprintf(&Buf1[i], 4, "%02x ", Buf[k]);
    printf(Buf1);
    free(Buf1);
}

9、逐级创建文件夹

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
int mkdir_recursively(char* dir) {
    if (NULL == dir)
        return 1;

    size_t len = strlen(dir);
    char* str = malloc(len + 1);

    if (NULL == str)
        return 1;

    strcpy(str, dir);
    int i = 0;
    for (i = 0; i < len; i++) {
        if (str[i] == '/') {
            if (i == 0)
                continue;
            str[i] = '\0';
            if (access(str, 0) != 0) {
                if (mkdir(str, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)) {
                    free(str);
                    return 1;
                }
            }
            str[i] = '/';
        }
    }

    if (len > 0 && access(str, 0) != 0) {
        if (mkdir(str, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)) {
            free(str);
            return 1;
        }
    }

    free(str);
    return 0;
}
int main() {
    mkdir_recursively("/home/test/abc/edf");
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值