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

}

相关推荐
白杨尚青5 分钟前
C++进阶篇(五):红黑树——四条规则、三种插入情况与旋转变色
开发语言·数据结构·c++·stl·红黑树·平衡二叉树
.道阻且长.12 分钟前
Linux基本开发工具:gdb和cgdb的使用
linux·运维·服务器·开发语言
starzy19901 小时前
深入理解Scala匿名函数:函数式编程基石
开发语言·scala
旖旎夜光1 小时前
【C++ 基础入门】C++ 继承(上):概念、切片、隐藏、默认成员函数与友元
c++·笔记·学习
apcipot_rain2 小时前
C++转Java日记(05)
java·开发语言·c++
apcipot_rain10 小时前
C++转Java日记(04)
java·开发语言·c++
wuyk55510 小时前
Keil工具链-第05讲-启动文件与__main到底做了什么
c语言·stm32·单片机·嵌入式硬件·物联网
云和数据.ChenGuang12 小时前
LangGraph 异步 Node 的设计与写法实践
开发语言·人工智能·python·机器学习·php
WL学习笔记13 小时前
vector模拟实现
c++
蜗牛一步步往上爬15 小时前
第十六章 C++语言在深度学习中的应用
开发语言·c++·深度学习