Linux下常用的C语言代码片段


=Start=

缘由:

学习、提高需要

正文:

参考解答:

将文件内容整体读入一个字符串
https://stackoverflow.com/questions/174531/easiest-way-to-get-files-contents-in-c # malloc+fread / mmap
https://stackoverflow.com/questions/14002954/c-programming-how-to-read-the-whole-file-contents-into-a-buffer
https://stackoverflow.com/questions/3747086/reading-the-whole-text-file-into-a-char-array-in-c

char *file_to_str(const char *filename) {
    char *buffer = NULL;
    long length;
    FILE *f = fopen (filename, "rb");
    if (f) {
        fseek (f, 0, SEEK_END);
        length = ftell (f);
        fseek (f, 0, SEEK_SET);
        buffer = malloc (length);
        if (buffer) {
            fread (buffer, 1, length, f);
        }
        fclose (f);
    }
    return buffer;
}

去除行尾的换行符
https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input

line[strcspn(line, "\r\n")] = 0;    // remove trailing newline character

用C语言写文件
https://stackoverflow.com/questions/2008267/how-to-write-a-file-with-c-in-linux
https://stackoverflow.com/questions/24249369/how-to-write-pid-to-file-on-unix

# 先将int转换成char *类型(convert int to string first)然后写入

 

=END=

,

《“Linux下常用的C语言代码片段”》 有 4 条评论

  1. int const * a / int * const a / int const * const a的区别
    https://blog.saymagic.tech/2014/07/22/understand-c-const.html
    `
    int b = 2;
    int c = 3;
    int const * a =&b;
    a = &c;
    printf(“a :%d b:%d c: %d\n”, *a,b,c); // a :3 b:2 c: 3

    const在 * a的前面,就说明const是形容a的 ,也就是a所指向的值是不可以改变的,所以*a = c 或者b = c都会是编译不通过的。因此,此时我们尽量将b也声明为const,否则后面的代码如果不小心改变b的值也会出错。
    `

回复 a-z 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注