C/C++ 移动追加内容到文件尾部。

1、通过C语言文件函数库

1.1、通过追加到尾部字符命令

FILE* f = fopen(file_path.data(), "ab+");

1.2、不通过追加到尾部字符命令

FILE* f = fopen(path, "rb");

if (NULL != f)

{

fseek(f, 0, SEEK_END);

}

Unix 平台(Linux/Android/MacOS X)

2、通过 Lseek 函数

int fd = open(file_path.data(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);

if (fd != -1)

{

Lseek2(fd, 0, SEEK_END);

}

Impl

bool Lseek2(int fd, int64_t offset, int whence) noexcept { return Lseek(fd, offset, whence) != -1; }

int64_t Lseek(int fd, int64_t offset, int whence) noexcept {

if (fd == -1) {

return -1;

}

whence = std::max<int>(whence, SEEK_SET);

#if defined(__USE_GNU)

#if defined(SEEK_HOLE)

whence = std::min<int>(whence, SEEK_HOLE);

#elif defined(SEEK_DATA)

whence = std::min<int>(whence, SEEK_DATA);

#else

whence = std::min<int>(whence, SEEK_END);

#endif

#else

whence = std::min<int>(whence, SEEK_END);

#endif

#if defined(_MACOS)

// https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/lseek.2.html

return lseek(fd, offset, whence);

#else

#if defined(_LARGEFILE64_SOURCE)

// https://android.googlesource.com/platform/bionic/+/b23f193/libc/unistd/lseek64.c

int64_t r = lseek64(fd, offset, whence);

if (r != -1) {

return r;

}

#endif

return lseek(fd, offset, whence);

#endif

}

相关推荐
前端老石人6 分钟前
HTML 字符引用完全指南
开发语言·前端·html
matlab_xiaowang22 分钟前
Redux 入门:JavaScript 可预测状态管理库
开发语言·javascript·其他·ecmascript
虹科网络安全34 分钟前
艾体宝干货|数据复制详解:类型、原理与适用场景
java·开发语言·数据库
axng pmje1 小时前
Java语法进阶
java·开发语言·jvm
汉克老师1 小时前
GESP2025年3月认证C++五级( 第三部分编程题(1、平均分配))
c++·算法·贪心算法·排序·gesp5级·gesp五级
老前端的功夫1 小时前
【Java从入门到入土】28:Stream API:告别for循环的新时代
java·开发语言·python
qq_435287921 小时前
第9章 夸父逐日与后羿射日:死循环与进程终止?十个太阳同时值班的并行冲突
java·开发语言·git·死循环·进程终止·并行冲突·夸父逐日
止语Lab1 小时前
从手动到框架:Go DI 演进的三个拐点
开发语言·后端·golang
yaoxin5211232 小时前
397. Java 文件操作基础 - 创建常规文件与临时文件
java·开发语言·python
小短腿的代码世界2 小时前
Qt日志系统深度解析:从qDebug到企业级日志框架
开发语言·qt