Reputation: 201
in a C program I want to append data to a text file. Used the fopen function like this:
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 sometimes returns (ok), but the file is overwritten and not added.
Used the fopen function like this:
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++;
}
Data is added but GetLastErrorgives an error 183. Programm continues work correctly in both cases, but i use this code in postgre extension, and it crashes and lose connection server for unknown reasons. How to correctly add data to a file without error?
Upvotes: 0
Views: 106
Reputation: 7882
If you want your code to work as a PostgreSQL extension you should try to use the routines already available in PostgreSQL code that you can find in 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.
*/
This code is available on Linux and Windows.
You can find examples in pg_stat_statements extension source code: postgres/contrib/pg_stat_statements/pg_stat_statements.c
Upvotes: 1
Reputation: 1260
from Microsoft System Error Codes:
ERROR_ALREADY_EXISTS 183 (0xB7). Cannot create a file when that file already exists
I think that this is just a reminder that the file is already there.
Upvotes: 0