0

这几天我发布了一些与该问题相关的更多问题。只是现在我得到了一些非常有趣的东西。

看我的代码:

#include <libpq-fe.h>
#include <stdlib.h>
#include <string.h>

#define LINE_SIZE 100

PGconn *connect(char *);

int main() 
{
    connect("/path/to/file.props");
    return 0;
}

PGconn *connect(char *file_path) 
{
    const char **keywords;
    const char **values;
    char *line = malloc(LINE_SIZE);
    char *prop, *val, *tmp;
    int i = 0, j = 0, k = 0;
    PGconn *conn = NULL;
    FILE *creds = fopen(file_path, "r");
    
    if (creds == NULL) {
        perror("error: cannot open credentials file");   //!!! warning
        exit(1);
    }
    
    keywords = malloc(6 * sizeof(char *));
    values = malloc(6 * sizeof(char *));
    
    while (fgets(line, LINE_SIZE, creds) != NULL) {
        if (line[strlen(line) - 1] == '\n')
            line[strlen(line) - 1] = '\0';
        prop = line;
        while(*(prop++) != '=') {
            i++;
        }
        tmp = prop;
        prop = malloc(i + 1);
        strncpy(prop, line, i);
        prop[i] = '\0';
        keywords[j++] = prop;
        val = malloc(strlen(line) - strlen(prop) + 1);
        strcpy(val, tmp);
        values[k++] = val;
        i = 0;
    }
    keywords[j] = NULL;
    values[k] = NULL;
    printf("%s %s %s %s %s\n", keywords[0], keywords[1], keywords[2], keywords[3], keywords[4]);
    printf("%s %s %s %s %s\n", values[0], values[1], values[2], values[3], values[4]); //prints well
    conn = PQconnectdbParams(keywords, values, 0);
    if (PQstatus(conn) != CONNECTION_OK) {
        fprintf(stderr, "%s\n", PQerrorMessage(conn));
        exit(1);
    }
    
    return conn;
}

当我运行它时,我得到以下输出:

hostaddr 端口 用户密码 dbname

127.0.0.1 5432 my_user my_password my_db

错误:无法打开凭据文件:地址错误

如您所见,文件内容被打印出来,并且只有在其内容被打印出来之后,上面的错误(来自带有“警告”注释的行)才会被打印出来,就像无法读取该文件一样。

你知道这里会发生什么吗?

4

1 回答 1

7

“connect”是连接到套接字的系统调用。我假设 PQconnextdbParams 可能会尝试使用“连接”并再次定向到您的函数。尝试将函数重命名为“myconnect”。

于 2013-02-25T14:46:07.977 回答