add functions fc_safe_write_file_init/open/close

pull/37/merge
YuQing 2021-10-10 14:43:38 +08:00
parent a439b8e62d
commit 09e00bcf5e
4 changed files with 70 additions and 1 deletions

View File

@ -1,5 +1,5 @@
Version 1.54 2021-09-22 Version 1.54 2021-10-10
* fast_allocator.[hc]: correct reclaim_interval logic * fast_allocator.[hc]: correct reclaim_interval logic
* shared_func.[hc]: add functions getFileContentEx1 and getFileContent1 * shared_func.[hc]: add functions getFileContentEx1 and getFileContent1
* fc_queue.[hc]: add function fc_queue_timedpeek * fc_queue.[hc]: add function fc_queue_timedpeek

View File

@ -280,6 +280,12 @@ typedef struct
string_t s; string_t s;
} FilenameString; } FilenameString;
typedef struct {
char *filename;
char *tmp_filename;
int fd;
} SafeWriteFileInfo;
typedef void (*FreeDataFunc)(void *ptr); typedef void (*FreeDataFunc)(void *ptr);
typedef int (*CompareFunc)(void *p1, void *p2); typedef int (*CompareFunc)(void *p1, void *p2);
typedef void* (*MallocFunc)(size_t size); typedef void* (*MallocFunc)(size_t size);

View File

@ -3630,3 +3630,27 @@ bool is_digital_string(const char *str)
return true; return true;
} }
int fc_safe_write_file_init(SafeWriteFileInfo *fi,
const char *file_path, const char *redo_filename,
const char *tmp_filename)
{
char full_filename[PATH_MAX];
snprintf(full_filename, sizeof(full_filename), "%s/%s",
file_path, redo_filename);
if ((fi->filename=fc_strdup(full_filename)) == NULL)
{
return ENOMEM;
}
snprintf(full_filename, sizeof(full_filename), "%s/%s",
file_path, tmp_filename);
if ((fi->tmp_filename=fc_strdup(full_filename)) == NULL)
{
return ENOMEM;
}
fi->fd = -1;
return 0;
}

View File

@ -1131,6 +1131,45 @@ int fc_check_filename(const string_t *filename, const char *caption);
*/ */
bool is_digital_string(const char *str); bool is_digital_string(const char *str);
int fc_safe_write_file_init(SafeWriteFileInfo *fi,
const char *file_path, const char *redo_filename,
const char *tmp_filename);
static inline int fc_safe_write_file_open(SafeWriteFileInfo *fi)
{
const int flags = O_WRONLY | O_CREAT | O_TRUNC;
int result;
if ((fi->fd=open(fi->tmp_filename, flags, 0644)) < 0) {
result = errno != 0 ? errno : EIO;
logError("file: "__FILE__", line: %d, "
"open file %s fail, errno: %d, error info: %s",
__LINE__, fi->tmp_filename, result, STRERROR(result));
return result;
} else {
return 0;
}
}
static inline int fc_safe_write_file_close(SafeWriteFileInfo *fi)
{
int result;
close(fi->fd);
if (rename(fi->tmp_filename, fi->filename) != 0)
{
result = errno != 0 ? errno : EIO;
logError("file: "__FILE__", line: %d, "
"rename file \"%s\" to \"%s\" fail, "
"errno: %d, error info: %s", __LINE__,
fi->tmp_filename, fi->filename,
result, STRERROR(result));
return result;
} else {
return 0;
}
}
static inline int fc_check_realloc_iovec_array( static inline int fc_check_realloc_iovec_array(
iovec_array_t *array, const int target_size) iovec_array_t *array, const int target_size)
{ {