如果您深入研究标题,您会在以下位置找到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;
所以这是你对text
数据类型的定义。请注意评论中这个相当重要的部分:
没有终止 null 或类似的东西
这表明您绝对不想将fileName->data
其视为 C 字符串,除非您喜欢 segfaults。您需要一种将 a 转换为text
可以交给的以空字符结尾的 C 字符串的方法stat
;有一个功能:text_to_cstring
。
text_to_cstring
我能找到的唯一文档是源代码中的这条评论:
/*
* text_to_cstring
*
* Create a palloc'd, null-terminated C string from a text value.
*
* We support being passed a compressed or toasted text value.
* This is a bit bogus since such values shouldn't really be referred to as
* "text *", but it seems useful for robustness. If we didn't handle that
* case here, we'd need another routine that did, anyway.
*/
还有一个使用它的例子:
char *command;
/*...*/
/* Convert given text object to a C string */
command = text_to_cstring(sql);
/*...*/
pfree(command);
你应该能够做这样的事情:
struct stat buf;
char *fileName = text_to_cstring(PG_GETARG_TEXT_P(0));
int i = stat(fileName, &buf);
pfree(fileName);