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 小时前
GESP2024年6月认证C++二级( 第一部分选择题(9-15))
c++·循环结构·分支结构·gesp二级·gesp2级·求余数
清水白石0086 小时前
突破并行瓶颈:Python 多进程开销全解析与 IPC 优化实战
开发语言·网络·python
王老师青少年编程7 小时前
csp信奥赛c++高频考点假期集训(分模块进阶)
数据结构·c++·算法·csp·高频考点·信奥赛·集训
百锦再7 小时前
Java之Volatile 关键字全方位解析:从底层原理到最佳实践
java·开发语言·spring boot·struts·kafka·tomcat·maven
daad7777 小时前
rcu 内核线程
java·开发语言
z20348315207 小时前
如何通过状态机解决按键识别问题(二)
c语言·单片机·嵌入式硬件
xzjiang_3657 小时前
检查是否安装了MinGW 编译器
开发语言·qt·visual studio code
王老师青少年编程8 小时前
2020年信奥赛C++提高组csp-s初赛真题及答案解析(选择题1-5)
c++·题解·真题·初赛·信奥赛·csp-s·提高组
百锦再8 小时前
Java JUC并发编程全面解析:从原理到实战
java·开发语言·spring boot·struts·kafka·tomcat·maven
清水白石0088 小时前
突破性能瓶颈:深度解析 Numba 如何让 Python 飙到 C 语言的速度
开发语言·python