Linux下的C语言实现#将文件内容读入数组


=Start=

缘由:

要实现一个daemon程序,提供类似Nginx的reload功能(即,对其发送USR1信号,它会自动重新加载配置文件并实时生效),信号处理部分已经知道该如何处理了,现在就是在接收到信号后去读取文件内容并更新全局变量使即时生效。

正文:

参考解答:

初始代码是这样的:

int pid_list[16] = { [ 0 ... 15 ] = -1 };
int usr1_reload() {
   FILE *fp;
   fp = fopen("/tmp/pmon.txt""r");
   if (fp == NULL) {
       perror("fopen");
       return -1;
   }
   char *line = NULL;
   size_t len = 0;
   ssize_t nread;
   int i = 0;
   while (((nread = getline(&line, &len, fp)) != -1) && i < 16) {
       pid_list[i++] = atoi(line); //atoi()在对一个非数字字符串进行转换时只会返回0,但没有错误信息,所以不推荐使用
   }
   if(line)
       free(line);
   fclose(fp);
   return 0;
}

&

{
    /* some code here */
    char *line = NULL, *index = NULL;
    char pid_str[1024] = {0}, *pid_str_p, *token = NULL, delim[] = ", ";
    size_t len = 0;
    ssize_t nread;
    int i = 0, pid;
    while ((nread = getline(&line, &len, fp)) != -1) {
        if (strncmp(line, "pid", 3) == 0) {
            index = strchr(line, '=');
            if (index) {
                strncpy(pid_str, index+1, nread-6);
                pid_str_p = pid_str;
                token = strsep(&pid_str_p, delim);
                while(token != NULL){
                    if (token[0] != '\0') {
                      pid = (int) strtol(token, NULL, 10);
                      if (pid <= 0 || pid == (int)LONG_MIN || pid == (int)LONG_MAX) {
                      } else {
                        if (i < MAX_PID_COUNT-1) {
                          pid_list[i++] = pid;
                        }
                      }
                    }
                    token = strsep(&pid_str_p, delim);
                }
            }

            break;
        }
    }
    /* some code here */
}

 

参考链接:

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

Linux下C语言中整型数的范围
linux c integer range
https://stackoverflow.com/questions/6155784/range-of-values-in-c-int-and-long-32-64-bits
https://stackoverflow.com/questions/11438794/is-the-size-of-c-int-2-bytes-or-4-bytes

Linux下C语言中的 atoi() 和 strtol()
linux c atoi error string
https://stackoverflow.com/questions/2024648/convert-a-string-to-int-but-only-if-really-is-an-int
http://man7.org/linux/man-pages/man3/strtol.3.html
https://stackoverflow.com/questions/8871711/atoi-how-to-identify-the-difference-between-zero-and-error
https://stackoverflow.com/questions/2729460/why-do-i-get-this-unexpected-result-using-atoi-in-c

=END=

,

《“Linux下的C语言实现#将文件内容读入数组”》 有 1 条评论

发表回复

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