C语言中的文件、字符串操作


=Start=

缘由:

最近在Linux环境下用C语言实现一些功能,在完成工作任务的同时学习、收藏了一些经典的代码片段/链接,想到以后可能会用到,所以在功能实现之后又重新梳理了一下相关内容并整理至此,方便以后碰到类似需求的时候能快速上手。

正文:
1.用getline函数循环读取文件内容
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    FILE *fp;
    char *line = NULL;
    size_t len = 0;
    ssize_t read;

   fp = fopen("/etc/motd", "r");
    if (fp == NULL)
        exit(EXIT_FAILURE);

   while ((read = getline(&line, &len, fp)) != -1) {
        printf("Retrieved line of length %zu :'%s'\n", read, line); /* 在line中包含了一个换行符'\n'*/
    }

   free(line);
   exit(EXIT_SUCCESS);
}

另外还有fgets函数,一般用于固定格式(每行长度)文件的读取,你可以根据具体情况决定是否选用:

#include <stdio.h>
#include <stdlib.h>

int main (void) {
    char buf[256];
    while (fgets (buf, sizeof(buf), stdin)) {
        printf("line: %s", buf);
    }
    if (ferror(stdin)) {
        fprintf(stderr,"Oops, error reading stdin\n");
        abort();
    }
    return 0;
}
2.如何判断字符串指针为空/指向的内容为空

首先检查该字符串指针是否为NULL,然后看该字符串指针指向内容的第一个字符是否为「\0」来进行判断:

char *c = "";
if ((c != NULL) && (c[0] == '\0')) {
    printf("c is empty\n");
}
3.用sscanf函数进行字符串截取
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char src_ip[16];
    char * ssh_client = NULL;
    if ((getenv ("SSH_CLIENT"))) {
        ssh_client = getenv ("SSH_CLIENT");
        printf("SSH_CLIENT = %s\n", ssh_client);
    }

    if ( ssh_client != NULL ) {
        printf("SSH_CLIENT = %s\n", ssh_client);
        sscanf(ssh_client, "%15[^ ]", src_ip);  // 取 ssh_client 变量指向的字符串中从开头到第一个空白字符之间的最多15个字符存入 src_ip 变量中
        printf("SRC_IP\t= %s\n", src_ip);
    } else {
        printf("SSH_CLIENT = null\n");
    }
    return 0;
}
4.用strncpy函数进行字符串复制
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
    char * ssh_client = (char *)NULL;
    char src_ip[16] = "";
    if ( ssh_client != NULL ) {
        sscanf(ssh_client, "%15[^ ]", src_ip);
    } else {
        // src_ip = "null";
        strncpy(src_ip, "null", 15);//这里需要用strncpy函数进行字符串数组赋值,上面那行的操作是错误的!
    }
    printf("src_ip = %s\n", src_ip);
    return 0;
}
5.将 字符串指针 转换成 字符串数组
6.将 字符串数组 转换成 字符串指针
7.字符串数组的初始化

……不定期更新……

=END=

, ,

《“C语言中的文件、字符串操作”》 有 8 条评论

  1. ##字符串处理##
       http://c.biancheng.net/cpp/u/hs2/
       https://randu.org/tutorials/c/strings.php
       https://www.byvoid.com/blog/c-string
    字符串截取(strncpy / strstr / sscanf)
    字符串分割(strtok / strsep)
    字符串复制(strcpy / strncpy / strlcpy)
    字符串连接(strcpy / strncpy / memcpy / strcat / strncat)
    字符串比较(strcmp / strcasecmp)
    字符串包含(strstr / strrchr)
    字符串初始化
       http://stackoverflow.com/questions/18688971/c-char-array-initialization
       http://stackoverflow.com/questions/963911/how-to-initialize-char-array-from-a-string

    ##文件处理##
    文件内容读取
       http://stackoverflow.com/questions/174531/easiest-way-to-get-files-contents-in-c
       http://stackoverflow.com/questions/14002954/c-programming-how-to-read-the-whole-file-contents-into-a-buffer
       http://stackoverflow.com/questions/3463426/in-c-how-should-i-read-a-text-file-and-print-all-strings
       https://linux.die.net/man/3/getline

  2. 在C语言中如何检查某个字符串是以指定字符串开头的?
    `
    bool startsWith(const char *pre, const char *str)
    {
    size_t lenpre = strlen(pre), lenstr = strlen(str);
    return lenstr < lenpre ? false : strncmp(pre, str, lenpre) == 0;
    }
    `
    http://stackoverflow.com/questions/4770985/how-to-check-if-a-string-starts-with-another-string-in-c

    在C语言中如何比较两个字符串是否相同?
    `
    strcmp(check, input) != 0 // 不等于0则两个字符串不相同
    `
    https://linux.die.net/man/3/strcmp
    http://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c

  3. 一定要在 strcat() 之前使用 strcpy() 么? #不一定
    https://stackoverflow.com/questions/18838933/why-do-i-first-have-to-strcpy-before-strcat
    http://www.iteedu.com/os/linux/linuxprgm/linuxcfunctions/memstring/strcat.php
    `
    strcat()会查找终止符(‘\0’)作为字符串的结尾,并将字符串从该位置起开始添加,会覆盖终止符(‘\0’),并在连接的最后添加终止符(‘\0’)。
    在 char stuff[100]; 这种情况下, stuff 没有被初始化,因此它可能是以 NUL 开头的,也可能不包含 NUL (换言之:行为未定义就不可控),所以要么主动初始化——手动添加 NUL ,要么通过调用 strcpy 让它帮忙添加 NUL 。
    `

  4. C语言中(整数、字符)数组元素的初始化
    https://stackoverflow.com/questions/201101/how-to-initialize-all-members-of-an-array-to-the-same-value
    https://stackoverflow.com/questions/2589749/how-to-initialize-array-to-0-in-c
    `
    // int ids[ID_SIZE] = { -1 }, i;
    // for (i = 0; i < ID_SIZE; ++i) {
    // printf("ids[%d] = %d\n", i, ids[i]); // -1,0,0,0,…
    // }

    // int ids[ID_SIZE] = { [0 … 31] = -1 }, i;
    // for (i = 0; i < ID_SIZE; ++i) {
    // printf("ids[%d] = %d\n", i, ids[i]); // -1,-1,-1,-1,…
    // }

    int ids[ID_SIZE], i;
    for (i = 0; i < ID_SIZE; ++i) {
    ids[i] = -1;
    printf("ids[%d] = %d\n", i, ids[i]); // -1,-1,-1,-1,…
    }

    char zeroArray[1024] = {0};
    `

  5. C语言fscanf()函数:输入函数(比较常用)
    http://c.biancheng.net/cpp/html/292.html
    http://wiki.jikexueyuan.com/project/c/fscanf.html
    http://man7.org/linux/man-pages/man3/fscanf.3.html#RETURN_VALUE
    https://stackoverflow.com/questions/tagged/fscanf?sort=votes&pageSize=15
    `
    返回值:如果成功,该函数返回成功匹配和赋值的个数。如果到达文件末尾或发生读错误,则返回 EOF ,错误原因存于errno中。
    `

    fscanf的返回值、错误信息判断
    https://stackoverflow.com/questions/3351809/reading-file-using-fscanf-in-c/3351926#3351926

回复 a-z 取消回复

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