在C++中,进行Linux文件操作主要依赖于POSIX标准库中的<fcntl.h>、<unistd.h>、<sys/stat.h>、<sys/types.h>等头文件。以下是一些常用的Linux文件操作:
使用open()函数打开一个文件,并返回一个文件描述符。
#include <fcntl.h>
int fd = open(const char* pathname, int flags);
// flags可以是O_RDONLY, O_WRONLY, O_RDWR等
使用close()函数关闭一个已打开的文件描述符。
#include <unistd.h>
int close(int fd);
使用read()函数从文件描述符中读取数据。
#include <unistd.h>
ssize_t read(int fd, void* buf, size_t count);
使用write()函数向文件描述符中写入数据。
#include <unistd.h>
ssize_t write(int fd, const void* buf, size_t count);
使用lseek()函数移动文件指针。
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
// whence可以是SEEK_SET, SEEK_CUR, SEEK_END
使用fstat()函数获取文件的状态信息。
#include <sys/stat.h>
int fstat(int fd, struct stat* buf);
使用open()函数的O_CREAT标志创建一个新文件。
int fd = open(const char* pathname, int flags, mode_t mode);
// mode可以是S_IRUSR, S_IWUSR等权限掩码
使用remove()函数删除一个文件。
#include <unistd.h>
int remove(const char* pathname);
使用rename()函数重命名一个文件。
#include <unistd.h>
int rename(const char* oldpath, const char* newpath);
使用link()函数创建一个硬链接。
#include <unistd.h>
int link(const char* oldpath, const char* newpath);
使用symlink()函数创建一个符号链接。
#include <unistd.h>
int symlink(const char* target, const char* linkpath);
使用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);
使用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++文件操作的基本方法,根据具体需求可以选择合适的函数进行使用。