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

}

相关推荐
零号全栈寒江独钓几秒前
visual studio编译wxWidgets
c++·visual studio
努力中的编程者2 分钟前
哈希表(C语言底层实现)
c语言·数据结构·c++·算法·哈希算法·散列表
2501_921649494 分钟前
全球股票行情API:如何高效获取实时与逐笔成交数据
开发语言·后端·python·金融·restful
mjhcsp5 分钟前
C++ 迭代加深搜索(IDDFS):从原理到实战的深度解析
c++·深度优先·迭代加深
甘露s5 分钟前
新手入门:传统 Web 开发与前后端分离开发的区别
开发语言·前端·后端·web
快乐得小萝卜9 分钟前
记录: python-cpp数据验证
开发语言·python
lsx20240611 分钟前
C语言中的递归
开发语言
福大大架构师每日一题13 分钟前
2026年3月TIOBE编程语言排行榜,Go语言排名第16,Rust语言排名14。为什么 TIOBE 指数仍然依赖搜索引擎?
开发语言·搜索引擎·rust·tiobe
摆烂小白敲代码15 分钟前
【数据结构与算法】汉诺塔问题(C++)
c语言·开发语言·数据结构·c++·算法·hanoi·汉诺塔问题
Bert.Cai16 分钟前
Python字符串strip函数作用
开发语言·python