linux cpp文件操作:stat/open

文章介绍了在Linux中用于获取文件信息的系统调用fstat,stat和lstat,以及structstat结构体的使用。structstat包含文件的设备ID、inode、权限模式、大小、修改时间等信息。fstat使用文件描述符获取信息,stat和lstat则根据路径,lstat能识别符号链接。
摘要由CSDN通过智能技术生成

struct stat

#include <sys/stat.h>

// some useful member
struct stat {
	dev_t           st_dev;         /* [XSI] ID of device containing file */
	ino_t           st_ino;         /* [XSI] File serial number */
	mode_t          st_mode;        /* [XSI] Mode of file (see below) */
	nlink_t         st_nlink;       /* [XSI] Number of hard links */
	uid_t           st_uid;         /* [XSI] User ID of the file */
	gid_t           st_gid;         /* [XSI] Group ID of the file */
	dev_t           st_rdev;        /* [XSI] Device ID */
	time_t          st_atime;       /* [XSI] Time of last access */
	long            st_atimensec;   /* nsec of last access */
	time_t          st_mtime;       /* [XSI] Last data modification time */
	long            st_mtimensec;   /* last data modification nsec */
	time_t          st_ctime;       /* [XSI] Time of last status change */
	long            st_ctimensec;   /* nsec of last status change */
	off_t           st_size;        /* [XSI] file size, in bytes */
	blkcnt_t        st_blocks;      /* [XSI] blocks allocated for file */
	blksize_t       st_blksize;     /* [XSI] optimal blocksize for I/O */
};

st_mode include some cases:
S_IFSOCK		socket
S_IFLINK		symbol link
S_IFDIR			if dictionary

the difference between lstat/fstat/stat

int fstat(int filedes, struct stat* buf);
int stat(const char* path, struct stat* buf);
int lstat(const char* path, struct stat* buf);

fstat need a file descriptor, so we should use open at first;
lstat means “link + stat”, so it can find if this file is symbolic link file;
when stat encounter a symbolic link file, it just go to the file referred to by the link directly.

use stat()

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

int main(){
	struct stat buf;
	stat("/etc/hosts", &buf);
	cout << "/etc/hosts file's size is " << buf.size << endl;

some function about st_mode

#define S_ISBLK(m)      (((m) & S_IFMT) == S_IFBLK)     /* block special */
#define S_ISCHR(m)      (((m) & S_IFMT) == S_IFCHR)     /* char special */
#define S_ISDIR(m)      (((m) & S_IFMT) == S_IFDIR)     /* directory */
#define S_ISFIFO(m)     (((m) & S_IFMT) == S_IFIFO)     /* fifo or socket */
#define S_ISREG(m)      (((m) & S_IFMT) == S_IFREG)     /* regular file */
#define S_ISLNK(m)      (((m) & S_IFMT) == S_IFLNK)     /* symbolic link */
#define S_ISSOCK(m)     (((m) & S_IFMT) == S_IFSOCK)    /* socket */
#if !defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE)
#define S_ISWHT(m)      (((m) & S_IFMT) == S_IFWHT)     /* OBSOLETE: whiteout */

use it

int main(){
	struct stat buf;
	int res = stat("/etc/hosts", &buf);
	if(0 != res){
		cout < "error" << endl;
	}
	if(S_ISDIR(buf.st_mode)){
		cout << "this file is a dic" << endl;
	}
}

some flags in open()

/* open-only flags */
#define O_RDONLY        0x0000          /* open for reading only */
#define O_WRONLY        0x0001          /* open for writing only */
#define O_RDWR          0x0002          /* open for reading and writing */
#define O_ACCMODE       0x0003          /* mask for above modes */
#define O_NONBLOCK      0x00000004      /* no delay */
#define O_APPEND        0x00000008      /* set append mode */
#define O_SHLOCK        0x00000010      /* open with shared file lock */
#define O_EXLOCK        0x00000020      /* open with exclusive file lock */
#define O_ASYNC         0x00000040      /* signal pgrp when data ready */
#define O_FSYNC         O_SYNC          /* source compatibility: do not use */
#define O_NOFOLLOW      0x00000100      /* don't follow symlinks */
#define O_CREAT         0x00000200      /* create if nonexistant */
#define O_TRUNC         0x00000400      /* truncate to zero length */
#define O_EXCL          0x00000800      /* error if already exists */
#define O_SYMLINK       0x00200000      /* allow open of a symlink */
#define O_NOFOLLOW_ANY  0x20000000      /* no symlinks allowed in path */

use exemple

int main(){
	int fileFd = open("/etc/hosts", O_RDONLY);		// read only
}
Linux环境下,使用C语言或C++操作文件通常涉及到I/O系统库函数。以下是一些基本操作: **删除文件**: - C/C++ (使用`unistd.h`库): ```cpp #include <unistd.h> int unlink(const char* filename); // 删除文件 ``` 例如: ```cpp unlink("path/to/file"); ``` - 错误处理很重要,因为`unlink()`可能会失败,这时可以检查返回值或者使用`errno`。 **创建文件**: - 使用`open()`和`creat()`函数创建新文件(仅C库): ```cpp #include <fcntl.h> #include <unistd.h> off_t creat(const char *pathname, mode_t mode); ``` 例如: ```cpp int fd = creat("path/to/newfile", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fd == -1) { perror("Error creating file"); } ``` - C++中可以使用`ofstream`类: ```cpp #include <fstream> ofstream file("path/to/newfile"); if (!file) { std::cerr << "Failed to create file" << std::endl; } file.close(); ``` **复制文件**: - 使用C的`rename()`或`copy_file_range()`(从C11开始可用): ```cpp #include <sys/stat.h> #include <sys/types.h> int rename(const char *oldpath, const char *newpath); // 或者 ssize_t copy_file_range(int out_fd, int in_fd, off_t out_offset, off_t in_offset, size_t count); ``` - C++可以使用`std::ifstream`, `std::ofstream`和`std::copy_n()`: ```cpp #include <fstream> std::ifstream in("sourcefile"); std::ofstream out("destinationfile"); std::copy(in.rdbuf()->in(), in.rdbuf()->end(), out.rdbuf()); in.close(); out.close(); ``` 记得始终处理可能出现的错误和异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值