1.5 read函数
#include<unistd.h>
ssize_t read(int fd, void *buf, size_t count);
功能:
把指定数目的数据读到内存(缓冲区)。
参数:
fd:文件描述符
buf:内存首地址
count:读取的字节个数
返回值:
成功:实际读取到的字节个数
失败:-1
代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#define BUFFER_SIZE 1024
int main() {
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("Failed to open the file");
exit(1);
}
char buffer[BUFFER_SIZE];
ssize_t bytes_read = read(fd, buffer, BUFFER_SIZE);
if (bytes_read == -1) {
perror("Failed to read from the file");
exit(1);
}
// 在这里可以继续处理读取的数据
if (close(fd) == -1) {
perror("Failed to close the file");
exit(1);
}
return 0;
}
1.6 stat函数
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char* path, struct stat* buf);
int lstat(const char* pathname, struct stat* buf);
功能:
获取文件状态信息
stat和lstat的区别:
当文件是一个符号链接时,lstat返回的是该符号链接本身的信息;
而stat返回的是该链接指向的文件的信息。
参数:
path:文件名
buf:保存文件信息的结构体
返回值:
成功: 0
失败: -1
代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
struct stat st;
if (stat("example.txt", &st) == -1) {
perror("Failed to get file status");
exit(1);
}
// 在这里可以继续处理文件状态信息
return 0;
}
1.7 dup、dup2函数
dup函数
#include<unistd.h>
int dup(int oldfd);
功能:
通过oldfd复制出一个新的文件描述符,新的文件描述符是调用进程文件描述符表中最小可用的文件描述符,最终oldfd和新的文件描述符都指向同一个文件。
参数:
oldfd:需要复制的文件描述符oldfd
返回值:
成功:新的文件描述符
失败:-1
dup2函数
#include<unistd.h>
int dup2(int oldfd, int newfd);
功能:
通过oldfd复制出一个新的文件描述符newfd,如果成功,newfd和函数返回值是同一个返回值,最终oldfd和新的文件描述符newfd都指向同一个文件。
参数:
oldfd:需要复制的文件描述符
newfd:新的文件描述符,这个描述符可以人为指定一个合法的数字(0-1023),如果指定的数字已经被占用(和某个文件有关联),此函数会自动关闭close()断开这个数字和某个文件的关联,再来使用这个合法数字。
返回值:
成功:返回newfd
失败:-1
代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("example.txt", O_WRONLY | O_CREAT, 0644);
if (fd == -1) {
perror("Failed to open the file");
exit(1);
}
// 复制文件描述符
int new_fd = dup(fd);
if (new_fd == -1) {
perror("Failed to duplicate file descriptor");
exit(1);
}
// 在这里可以继续处理文件描述符
if (close(fd) == -1) {
perror("Failed to close the file");
exit(1);
}
if (close(new_fd) == -1) {
perror("Failed to close the duplicated file");
exit(1);
}
return 0;
}
1.8 fcntl函数
#include<unistd.h>
#include<fcntl.h>
int fcntl(int fd, int cmd, .../* arg */);
功能:
改变已打开的文件性质,fcntl针对描述符提供控制。
参数:
fd:操作的文件描述符
cmd:操作方法
arg:针对cmd的值,fcntl能够接受第三个参数int arg
返回值:
成功:返回某个其他值
失败:-1
代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int main() {
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("Failed to open the file");
exit(1);
}
// 获取文件状态标志
int flags = fcntl(fd, F_GETFL);
if (flags == -1) {
perror("Failed to get file flags");
exit(1);
}
// 在这里可以继续处理文件状态标志
if (close(fd) == -1) {
perror("Failed to close the file");
exit(1);
}
return 0;
}