C 测试是否存在带有Postgres的文件
我需要创建一个函数来测试是否存在带有postgres的文件。我是用C语言做的,但我有个问题。代码是:C 测试是否存在带有Postgres的文件,c,postgresql,C,Postgresql,我需要创建一个函数来测试是否存在带有postgres的文件。我是用C语言做的,但我有个问题。代码是: #include "postgres.h" #include <string.h> #include "fmgr.h" #include <stdio.h> #include<sys/stat.h> #ifdef PG_MODULE_MAGIC PG_MODULE_MAGIC; #endif /* by value */ PG_FUNCTION_INFO
#include "postgres.h"
#include <string.h>
#include "fmgr.h"
#include <stdio.h>
#include<sys/stat.h>
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
/* by value */
PG_FUNCTION_INFO_V1(file_exists);
Datum
file_exists (PG_FUNCTION_ARGS)
{
text *fileName= PG_GETARG_TEXT_P(0);
struct stat buf;
int i = stat(fileName, &buf);
/* File found */
if ( i == 0 )
{
PG_RETURN_INT32(1);
}
PG_RETURN_INT32(0);
}
#包括“postgres.h”
#包括
#包括“fmgr.h”
#包括
#包括
#ifdef PG_模块
PG_模块_魔术;
#恩迪夫
/*按价值*/
PG_功能_信息_V1(文件_存在);
资料
文件存在(PG函数参数)
{
text*fileName=PG_GETARG_text_P(0);
结构统计buf;
int i=stat(文件名,&buf);
/*找到文件*/
如果(i==0)
{
PG_RETURN_INT32(1);
}
PG_RETURN_INT32(0);
}
我认为问题在于“stat”函数中的第一个参数,因为fileName是一个文本,而这个函数接收一个char
这是我第一次写C代码,所以可能一切都错了。如果你仔细阅读标题,你会在
server/C.h
中找到这个:
/* ----------------
* Variable-length datatypes all share the 'struct varlena' header.
*...
*/
struct varlena
{
char vl_len_[4]; /* Do not touch this field directly! */
char vl_dat[1];
};
#define VARHDRSZ ((int32) sizeof(int32))
/*
* These widely-used datatypes are just a varlena header and the data bytes.
* There is no terminating null or anything like that --- the data length is
* always VARSIZE(ptr) - VARHDRSZ.
*/
typedef struct varlena bytea;
typedef struct varlena text;
这就是您对文本
数据类型的定义。请注意评论中相当重要的一部分:
没有终止null或类似的东西
这表示您绝对不希望将fileName->data
视为C字符串,除非您喜欢。您需要一种方法将文本
转换为以nul结尾的C字符串,您可以将其交给stat
;这里有一个函数:text\u to\u cstring
我能找到的关于text\u to\u cstring
的唯一文档是:
还有:
您应该能够执行以下操作:
struct stat buf;
char *fileName = text_to_cstring(PG_GETARG_TEXT_P(0));
int i = stat(fileName, &buf);
pfree(fileName);
我也有同样的问题。text_to_cstring对我不起作用,然后我意识到问题是我没有包含text_to_cstring func的头文件。这太傻了。因此,我不得不在/usr/include/postgresql/your_version/server/utils/文件夹中搜索,直到我最终找到它,然后一切都很顺利。试一试
char *filename = text_to_cstring(PG_GETARG_TEXT_PP(0));
但是别忘了包括第一个内置的
#include "utils/builtins.h"
如何定义
text
?你不能用char*
代替text*
?我认为它是在postgresql.h中定义的,应该是这样的:typedef struct{int4 length;char data[1];}text;似乎很明显:只需引用fileName->data
而不是fileName
@netcoder:除了data
没有nul终止,所以将fileName->data
传递到stat
只是内存访问错误的快捷方式。您知道内置的pg\u stat\u file()
函数吗?
char *filename = text_to_cstring(PG_GETARG_TEXT_PP(0));
#include "utils/builtins.h"