这几天我发布了一些与此问题相关的问题。只有这一点,我才真正感兴趣。
查看我的代码:
#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
错误:无法打开凭证文件:地址错误
如您所见,文件内容已打印,只有在打印完内容后,才会打印上述错误(来自“警告”注释的行),因为该文件无法读取。
你对这里会发生什么有什么想法吗?
答案 0 :(得分:7)
“connect”是连接到套接字的系统调用。我假设PQconnextdbParams可能会尝试使用“connect”并再次定向到您的函数。尝试将该功能重命名为“myconnect”。