【问题标题】:How to add data to txt file in C?如何在C中将数据添加到txt文件?
【发布时间】:2020-08-07 20:03:16
【问题描述】:

在 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。 Programm 在这两种情况下都可以正常工作,但是我在 postgre 扩展中使用了这个代码,它会因为未知原因而崩溃并失去连接服务器。如何正确无误地将数据添加到文件中?

【问题讨论】:

  • 如果最后一个函数没有报错,GetLastError()有意义吗? fopen() 是否在 Windows 上设置了 win32 错误?
  • 你应该检查fopen()是否成功,检查它返回的指针是否为空。
  • 我认为因为GetLastError(),扩展正在下降,因为GetLastError() 仍然返回某种错误
  • @SovaKefirov 你不能混合使用fopen 等和GetLastError()。此外,GetLastError() 返回的错误号仅由记录设置它的 WINAPI 函数设置,并且仅在所述 WINAPI 函数失败时设置。
  • 为什么要混合 C++ 和 C?

标签: c file getlasterror


【解决方案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

【讨论】:

  • 我在哪里可以看到这些函数中的参数解释?我看到doxygen.postgresql.org 并浏览了互联网,但找不到好的示例或详细信息
  • AFAIK 的大部分文档实际上是源代码本身:有时函数有一个注释头,有时没有,有时有一个 README 文件,但最重要的是你拥有所有源代码:函数源代码本身,您还可以检查调用这些例程的代码的其他部分。如果您不知道,您可以在 PG 邮件列表中搜索或询问postgresql.org/list
【解决方案2】:

来自Microsoft System Error Codes:

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

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

【讨论】:

  • 我需要该文件存在并附加到它或从中读取
猜你喜欢
  • 2016-06-11
  • 1970-01-01
  • 2022-01-20
  • 2023-02-10
  • 1970-01-01
  • 1970-01-01
  • 2015-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多