温馨提示×

C++中Linux文件操作有哪些

小樊
45
2026-01-05 12:09:57
栏目: 编程语言

在C++中,进行Linux文件操作主要依赖于POSIX标准库中的<fcntl.h><unistd.h><sys/stat.h><sys/types.h>等头文件。以下是一些常用的Linux文件操作:

1. 打开文件

使用open()函数打开一个文件,并返回一个文件描述符。

#include <fcntl.h>

int fd = open(const char* pathname, int flags);
// flags可以是O_RDONLY, O_WRONLY, O_RDWR等

2. 关闭文件

使用close()函数关闭一个已打开的文件描述符。

#include <unistd.h>

int close(int fd);

3. 读取文件

使用read()函数从文件描述符中读取数据。

#include <unistd.h>

ssize_t read(int fd, void* buf, size_t count);

4. 写入文件

使用write()函数向文件描述符中写入数据。

#include <unistd.h>

ssize_t write(int fd, const void* buf, size_t count);

5. 文件定位

使用lseek()函数移动文件指针。

#include <unistd.h>

off_t lseek(int fd, off_t offset, int whence);
// whence可以是SEEK_SET, SEEK_CUR, SEEK_END

6. 文件状态信息

使用fstat()函数获取文件的状态信息。

#include <sys/stat.h>

int fstat(int fd, struct stat* buf);

7. 创建文件

使用open()函数的O_CREAT标志创建一个新文件。

int fd = open(const char* pathname, int flags, mode_t mode);
// mode可以是S_IRUSR, S_IWUSR等权限掩码

8. 删除文件

使用remove()函数删除一个文件。

#include <unistd.h>

int remove(const char* pathname);

9. 重命名文件

使用rename()函数重命名一个文件。

#include <unistd.h>

int rename(const char* oldpath, const char* newpath);

10. 链接文件

使用link()函数创建一个硬链接。

#include <unistd.h>

int link(const char* oldpath, const char* newpath);

11. 符号链接

使用symlink()函数创建一个符号链接。

#include <unistd.h>

int symlink(const char* target, const char* linkpath);

12. 目录操作

使用mkdir()创建目录,rmdir()删除目录,opendir()readdir()closedir()操作目录。

#include <sys/stat.h>
#include <dirent.h>

int mkdir(const char* pathname, mode_t mode);
int rmdir(const char* pathname);
DIR* opendir(const char* name);
struct dirent* readdir(DIR* dirp);
int closedir(DIR* dirp);

13. 文件权限和所有权

使用chmod()chown()chgrp()修改文件权限和所有权。

#include <sys/stat.h>
#include <unistd.h>

int chmod(const char* pathname, mode_t mode);
int chown(const char* pathname, uid_t owner, gid_t group);
int chgrp(const char* pathname, gid_t group);

注意事项

  • 在进行文件操作时,需要处理可能的错误情况,例如检查函数返回值。
  • 文件描述符在使用完毕后应及时关闭,以避免资源泄漏。
  • 在多线程环境中,对文件的并发访问需要进行适当的同步控制。

这些是Linux下C++文件操作的基本方法,根据具体需求可以选择合适的函数进行使用。

0