天天看点

C/C++学习笔记——文件操作(三)

date 2020-08-03

文件控制

#include<fcntl.h>

int fcntl (int fd ,int cmd,…);

1.复制文件描述符

int fcntl(int oldfd,F_DUPFD,newfd);

成功返回目标文件描述符(可能为newfd),失败返回-1

oldfd:源文件描述符

newfd: 目标文件描述符

fcntl函数在复制oldfd参数所标识的源文件描述符表项时,会先检查由newfd参数所标识的的目标文件描述符表项是否空闲,若空闲将前者复制给后者,否则并不会将其关闭,而是找另一个空闲的文件描述符作为复制目标

示例代码 fcntl.c

/*
date 2020-08-03
name fcntl.c
version 1.0
*/
#include<stdio.h>
#include<unistd.h>

           

2.获取/设置文件描述标志

int fcntl(int fd,F_SETFD,int flags);

成功返回0,失败返回-1

示例代码 fd.c

/*
date 2020-08-05
name fd.c
version 1.0
*/
#include<stdio.h>
#include<fcntl.h>
int main(void) {
	int fd = open("fd.txt",O_RWDR | O_CREAT | O_TRUNC,0644);
	if(-1 == fd){
		perror("open");
		return = -1; 
	}
	int flags = fcntl(fd,F_GETFD);
	if(-1 == flags) {
		perror("fcntl");
		return -1;
	}
	printf("文件描述符标志:%08x\n",flags);
	if(flags & FD_CLOEXE)
		printf("文件描述符%d将在新进程中被关闭。\n",fd);
	else
		printf("文件描述符%d将不会在新进程中关闭。\n",fd);
	if(fcntl(fd,F_SETFD,flags | FD_CLOEXEC) == -1) {
		perror("fcntl");
		return -1;
	}
	if((flags = fcntl(fd,F_GETFD) == -1) {
		perror("fcntl");
		return -1
	}	
	printf("文件描述符标志:%08x\n",flags);
	if(flags & FD_CLOEXE)
		printf("文件描述符%d将在新进程中被关闭。\n",fd);
	else
		printf("文件描述符%d将不会在新进程中关闭。\n",fd);
	close(fd);
	return 0 ;
}
           

文件锁

1.读写冲突

a.写冲突:如果有两个或两个以上的进程“同时”向一个文件的某个特定区域写数据,那么最后写入文件的数据极有可能因为写交错而产生混乱

b.读冲突:如果一个进程写而其他进程同时读一个文件的某个特定区域,那么读出来的数据极有可能因为读写操作的交错而不完整。

c.读共享:多个进程同时读一个文件的某个特定区域,不会有任何问题,它们只是各自把文件中的数据拷贝到各自的缓冲区去,并不会改变文件的内容,因此也就不会影响到彼此。