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=

声明: 除非注明,ixyzero.com文章均为原创,转载请以链接形式标明本文地址,谢谢!
https://ixyzero.com/blog/archives/3581.html

发表评论

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