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

}

相关推荐
明洞日记1 分钟前
【数据结构手册008】STL容器完全参考指南
开发语言·数据结构·c++
kingmax5421200817 分钟前
《数据结构C语言:单向链表-链表基本操作(尾插法建表、插入)》15分钟试讲教案【模版】
c语言·数据结构·链表
jllllyuz41 分钟前
matlab使用B样条进行曲线曲面拟合
开发语言·matlab
农夫山泉2号1 小时前
【c++】——c++编译的so中函数有额外的字符
java·服务器·c++
ku_code_ku1 小时前
python bert_score使用本地模型的方法
开发语言·python·bert
小马哥编程1 小时前
【软考架构】滑动窗口限流算法的原理是什么?
java·开发语言·架构
仰泳的熊猫1 小时前
1077 Kuchiguse
数据结构·c++·算法·pat考试
云栖梦泽1 小时前
鸿蒙数据持久化实战:构建本地存储与云同步系统
开发语言·鸿蒙系统
wjs20241 小时前
《Ionic 侧栏菜单》
开发语言
祁思妙想1 小时前
linux常用命令
开发语言·python