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

}

相关推荐
方华世界23 分钟前
企业级Java AI Agent应用平台
java·开发语言·人工智能
劉宇雁1 小时前
C++ ASCII 3D无尽跑酷游戏
c++·游戏·3d
ujainu小1 小时前
原生性能优化:6变量实现高效桥接
开发语言·华为·性能优化·harmonyos
甄同学1 小时前
第十七篇:Bash Executor命令执行器,安全运行Shell命令
开发语言·安全·bash
张3231 小时前
Go语言基础 Map 函数值 闭包
开发语言·golang
杜子不疼.1 小时前
【C++ 在线五子棋对战】- 会话管理模块实现
开发语言·c++
有点。1 小时前
C++深度优先搜索(DFS)的概念(一)
开发语言·c++·深度优先
旖-旎1 小时前
《LeetCode 978 最长湍流子数组 || LeetCode 139 单词拆分》
c++·算法·leetcode·动态规划
时间的拾荒人1 小时前
C语言编译与链接:从源码到可执行程序的完整解析
c语言·开发语言
人道领域1 小时前
【0-1的agent进阶篇】Prompt 与上下文工程
java·开发语言·prompt·mcp