代码示例:unix环境文件IO、出错处理

无干货,纯示例。

#include <fcntl.h>
#include <stdio.h>
int main(){
	//先试着打开一个不存在的文件
	char* filepath = "/home/kent/temp/test-file-io.txt";
	int fd = open(filepath, O_RDWR);
	printf("The File Descriptor of an non-existing files is %d \n", fd);
	if(fd == -1){	
		perror(filepath);	
	}	

	//创建文件
	fd = open(filepath, O_CREAT|O_RDWR, 0777);
	printf("The new created File Descriptor is %d \n", fd);

	//当前偏移量
	int pos = lseek(fd, 0, SEEK_CUR);
	printf("On creation, the position is %d \n", pos);	

	//写文件
	write(fd, "stop-talking-crazy",  12);
	fsync(fd); //确保内容已写入磁盘
	pos = lseek(fd, 0, SEEK_CUR);
	printf("After writing, the position is %d \n", pos);


	//读文件
	char buf[100];
	int n; 
	while((n = read(fd, buf, 10)) > 0){
		;
	}
	printf("The first element of the Buffer after read is %d\n", buf[0]);
	pos = lseek(fd, 0, SEEK_CUR);
	printf("After reading, the position is %d \n", pos);

	//应该从头开始读
	char new_buf[100];
	lseek(fd, 0, SEEK_SET);
	while((n = read(fd, new_buf, 100)) > 0){
		;
	}
	printf("The buffer read as %s \n", new_buf);
	pos = lseek(fd, 0, SEEK_CUR);
	printf("After reading from the beginning, the position is %d \n", pos);

	//关闭文件
	close(fd);

	//删除文件
	remove(filepath);
 
}

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.