0

在 C 程序中,我想将数据附加到文本文件中。像这样使用 fopen 函数:

FILE* fileLog;
char logFile_name[] = "C:\\pg\\log.txt";
fileLog = fopen(logFile_name, "r+");
int j = 0;
while (j < 4)
{
    fprintf(fileLog, "%u,%s", GetLastError(), "1_aba_1\n");
    j++;
}

GetLastError 有时会返回 (ok),但文件会被覆盖而不是添加。

像这样使用 fopen 函数:

FILE* fileLog;
char logFile_name[] = "C:\\pg\\log.txt";
fileLog = fopen(logFile_name, "a+");
std::cout << GetLastError() << " LOG \n";

int j = 0;
while (j < 3)
{
    fprintf(fileLog, "%u,%s", GetLastError(), "56_aba_4\n");
    j++;
}

添加了数据,但 GetLastError 给出错误 183。程序在这两种情况下都能正常工作,但我在 postgre 扩展中使用此代码,它崩溃并由于未知原因失去连接服务器。如何正确地将数据添加到文件中而不会出错?

4

2 回答 2

1

如果您希望您的代码作为 PostgreSQL 扩展工作,您应该尝试使用 PostgreSQL 代码中已有的例程,您可以在 postgres/src/include/storage/fd.h 中找到这些例程:

/*
 * calls:
 *
 *  File {Close, Read, Write, Size, Sync}
 *  {Path Name Open, Allocate, Free} File
 *
 * These are NOT JUST RENAMINGS OF THE UNIX ROUTINES.
 * Use them for all file activity...
 *
 *  File fd;
 *  fd = PathNameOpenFile("foo", O_RDONLY);
 *
 *  AllocateFile();
 *  FreeFile();
 *
 * Use AllocateFile, not fopen, if you need a stdio file (FILE*); then
 * use FreeFile, not fclose, to close it.  AVOID using stdio for files
 * that you intend to hold open for any length of time, since there is
 * no way for them to share kernel file descriptors with other files.
 *
 * Likewise, use AllocateDir/FreeDir, not opendir/closedir, to allocate
 * open directories (DIR*), and OpenTransientFile/CloseTransientFile for an
 * unbuffered file descriptor.
 *
 * If you really can't use any of the above, at least call AcquireExternalFD
 * or ReserveExternalFD to report any file descriptors that are held for any
 * length of time.  Failure to do so risks unnecessary EMFILE errors.
 */

此代码在 Linux 和 Windows 上可用。

您可以在 pg_stat_statements 扩展源代码中找到示例:postgres/contrib/pg_stat_statements/pg_stat_statements.c

于 2020-04-24T09:37:25.300 回答
0

来自Microsoft 系统错误代码:

ERROR_ALREADY_EXISTS 183 (0xB7)。当该文件已存在时无法创建该文件

我认为这只是一个提醒,文件已经存在。

于 2020-04-24T09:36:35.110 回答