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

}

相关推荐
知然7 小时前
鸿蒙 Native API 的封装库 h2lib_arkbinder
c++·arkts·鸿蒙
粟悟饭&龟波功7 小时前
Java—— ArrayList 和 LinkedList 详解
java·开发语言
冷雨夜中漫步7 小时前
Java中如何使用lambda表达式分类groupby
java·开发语言·windows·llama
十五年专注C++开发8 小时前
Qt .pro配置gcc相关命令(三):-W1、-L、-rpath和-rpath-link
linux·运维·c++·qt·cmake·跨平台编译
a4576368768 小时前
Objective-c Block 面试题
开发语言·macos·objective-c
Cai junhao8 小时前
【Qt】Qt控件
开发语言·c++·笔记·qt
uyeonashi8 小时前
【QT系统相关】QT网络
开发语言·网络·c++·qt
不过四级不改名6779 小时前
用c语言实现简易c语言扫雷游戏
c语言·算法·游戏
程序猿小D9 小时前
第27节 Node.js Buffer
linux·开发语言·vscode·node.js·c#·编辑器·vim
武昌库里写JAVA9 小时前
【微服务】134:SpringCloud
java·开发语言·spring boot·学习·课程设计