Linux 文件1.0—文件打开及其创建

针对文件的操作 Linux 系统 提供了很多 函数
包含于头文件
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

首先打开文件, 有两个 open 函数, 一个 creat 函数
int open (const char * pathname, int flags);
int open (const char * pathname, int flags, mode_t mode);

int creat(const char * pathname, mode_t mode);

描述:
描述:给一个文件的路径, open() 返回一个 文件的描述符,这个描述符是一个小的,非负的整数,为了后续的(subsequent)的系统的访问(calls) (比如说,读,写,光标移动, 布吉岛,等等)

int open (const char * pathname, int flags);
int open (const char * pathname, int flags, mode_t mode);

pathname 指的是文件名,(含路径,如果不写路径,那么默认为程序所在的路径) // 注: 当这里要输入路径时,以字符串的形式输入,即: " 123 "

flags 有三种:
O_RDONLY 只读打开
O_WRONLY 只写打开
O_RDWR 可读可写打开
flags 说明了权限,只读打开,便无法在后续函数中写,只写打开则无法读;

Linux touch命令用于修改文件或者目录的时间属性,包括存取时间和更改时间。若文件不存在,系统会建立一个新的文件。
Linux rm命令用于删除一个文件或者目录。

实际编程:

// 首先在Linux系统中输入 touch file1 创建一个文件 file1
// 然后输入代码
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
int main(){
	int fd;
	fd = open("./file1",O_RDWR);
	printf("fd = %d\n",fd);
	return 0;
}

/*
运行结果  fd = 3;
将  file1 删除:
rm file1
运行结果为: fd = -1;  也就是打开失败

此处注意一个 Linux的 或 操作
即:

// 将 file1 删除后
int main(){
	int fd;
	fd = open("./file1",O_RDWR);
	if(fd == -1){
		printf("open file1 failed \n");
		fd = open("./file1",O_RDWR | O_CREAT,0600);     
		if(fd > 0){
			printf("creat file1 \n");
		}
	}
	// 这里的 O_RDWR|O_CREAT 之间的 | 就是Linux的或操作            
	// 这里的 0600 即函数中的 mode 操作,之后讲解
	return 0;
}   // 注意要 gcc 哦

最后,我们再补充一个 Linux的操作 ls -l : 列出所有的文件清单

-rwxr-xr-x 1 CLC book     8427 Jul 19 00:46 a.out
-rw-r--r-- 1 CLC book     2013 May 20 21:50 error.c
-rw------- 1 CLC book        0 Jul 19 00:46 file1
-rwxr--r-- 1 CLC book      923 May 23 16:09 ground.c
-rwxrw-rw- 1 CLC book      882 May 23 13:14 ground.c.txt

解读:最前面的 - 代表这是一个普通文件,
      rwxr 代表 后面的 用户CLC 对这些文件的操作权限
      r可读,w可写,x可执行  
      可读是 4,可写是 2,可执行是 1
      所以之前的 0600 中的 6 代表 4+2 可读可写
      

对于:
#include<fcntl.h>
int creat (const char *pathname, mode_t mode)
此函数相当于
open(pathname, O_WRONLY|O_CREAT|O_TRUNC, mode)

create的不足之处是它以只写方式打开所创建的文件。在提供open的新版本之前如果要创建一个临时文件,并要写该文件,然后又读该文件,则必须先调用creat、close、open。现在则可用下列方式调用 open()
open(pathname, O_RDWR|O_CREAT|O_TRUNC, mode)

详情可查阅https://www.cnblogs.com/alionxd/articles/3011812.html

关于Linux权限,可查阅https://blog.csdn.net/nzing/article/details/9166057

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值