linux文件操作-1

linux下的七种文件

- 文件

d 目录

l 符号链接

s 套接字

b 块设备

c  字符设备

p 管道

伪文件是不占用磁盘空间的

常用的系统调用 umask

1.文件权限问题

如果open 给定一个文件权限 与 umask掩码 运算之后在赋予权限

当然 你也可以修改umask掩码   一个简单的demo

这个api非常简单 我们这里就不做演示了

来讨论一下lseek函数

1.这个函数是用来设置文件的文件指针位置的 大家都知道 一个文件只有一个文件指针,当你去写入一段数据之后,如果不重新设置一下文件的偏移,你在读的话 文件指针已经到了文件的末尾了,所以你是读不到数据的

2.这个函数还有第二个作用用来实现文件的拓展(不过在拓展之后要进行一次写的操作才行)

#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>

using namespace std;

int32_t
main(int argc, char* argv[])
{
	int32_t fd = open("./tmp", O_RDWR | O_CREAT | O_EXCL, 0644);
	if (fd < 0) {
		fprintf(stderr, "create file error the reason is %s\n", strerror(errno));
		exit(1);
	}

	int ret = lseek(fd, 0, SEEK_SET);
	printf("current offset location is %d\n", ret);

	// 设置文件扩展
	ret = lseek(fd, 200, SEEK_END);
	printf("current offset location is %d\n", ret);
	
	// 进行一次操作
	write(fd, "a", 1);
	close(fd);
	return 0;
}

效果如下:

我们来打开这个创建的文件来看看情况

看 a  就是在后面 先来介绍一个这个^@ 这个符号称为空洞符号,也许大家会感到陌生但是 如果你下载过小电影就知道

其实你下载的数据还没有收到 系统就已经在磁盘上创建了一个和你想要下载的文件同样大小的文件里面就是空洞符号,为什么要这样呢,因为你如果一遍下载一遍扩容的话,这样IO的处理效率就非常的底下,所以预先分配一块空间  你来了就往里面IO就行了

第二种扩容凡是 ftrucate / trucate

两者其实差不过  就是根据不同的方式操作而已 ,相比lseek 扩容之后是不用在进行一次写操作的

我们来通过一个简单的demo认识一下他吧 把上面的代码改动一下 吧lseek的部分注释掉,在创建一个tmp1的文件对它进行扩容

#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>

using namespace std;

int32_t
main(int argc, char* argv[])
{
	int32_t fd = open("./tmp1", O_RDWR | O_CREAT | O_EXCL, 0644);
	if (fd < 0) {
		fprintf(stderr, "create file error the reason is %s\n", strerror(errno));
		exit(1);
	}
	int ret = 0;
#if 0
	ret = lseek(fd, 0, SEEK_SET);
	printf("current offset location is %d\n", ret);

	// 设置文件扩展
	ret = lseek(fd, 200, SEEK_END);
	printf("current offset location is %d\n", ret);
	
	// 进行一次操作
	write(fd, "a", 1);
#else 
	ret = ftruncate(fd, 300);
	if (ret < 0) {
		fprintf(stderr, "exten file error the reason is %s\n", strerror(errno));
	}

#endif
	close(fd);
	return 0;
}

来看看tmp1:

其实这两个函数用起来都是非常简单的,后续的我会给大家介绍更多的 linux文件操作 ,目录操作, 进程相关(IPC为代表的),线程相关(同步异步之类为代表的)

网络相关(如多路io转接服务器,TCP的介绍),框架相关(Libevent  Libco(协程相关))

这里的话主要是给大家一个步入linuxC/C++开发的心里准备

更多的C/C++ linux编程我会在下面的文章中陆续的分享,也可以关注‘奇牛学院’

来一起讨论

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章