LINUX 文件编程 系统调用函数

如何使用系统调用函数creat(),open(),read(),write(),lseek(),close()对文件进行创建,打开,读写,关闭等操作。
摘要由CSDN通过智能技术生成

**

系统调用函数

**

open系列系统调用-creat

**

int creat(const char* pathname,mode_t mode)

**

在这里插入图片描述
例题:在/home/dhh/c.d目录下创建一个tttt.txt文件

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

void main()
{
   
	int fd=creat("/home/dhh/c.d/tttt.txt",0755);
	if(fd==-1)
	{
   
		printf("errno:%d\n",errno);
	}
	else
	{
   
		printf("fd:%d,create file successful! ",fd);
	}
}

注:0755->即表示用户具有读/写/执行(rwx)权限,组用户和其它用户具有读/执行(r-x)权限。

在程序运行前先ll查看c.d目录下的文件,没有tttt.txt
在这里插入图片描述
运行程序,成功,输出create file successful!
在这里插入图片描述
再次ll查看c.d目录,tttt.txt已被创建
在这里插入图片描述

**

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

**
mode_t指的是创建文件权限,比如上面说用到的0775。
flags是指打开文件的方式,一般是文件已经存在,用何种方式打开,一般主要有以下几种方式:
在这里插入图片描述
open函数其核心代码为:
int fd=open("/home/dhh/c.d/tttt.txt",O_RDWR|O_CREAT|O_EXCL,0755);

int close(int fd)

注:fd为文件操作符
当我们完成文件操作需要关闭文件,就要用到close函数
例题:打开一个文件然后关闭它

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>

void main()
{
   
	int state,fd;
	fd=open("/home/dhh/c.d/tttt.txt",O_RDWR|O_CREAT,0755);
	if(fd==-1)
	{
   
		printf("errno:%d,errno:%s\n",errno,strerror(errno));
		exit(EXIT_FAILURE);
	}
	else
	{
   
		printf("fd:%d,open file successful!\n ",fd);
	}
	state=close(fd);
		if(state==0)
		{
   
			printf("close file successful!\n");
		}
		else if(state==-1)
		{
   
			printf("errno:%d,errno:%s\n",errno,strerror(errno));
			exit(EXIT_FAILURE);
		}
}

在这里插入图片描述
说明文件被成功打开或关闭,若是出现错误无法打开则可以显示错误的代码和它所对应的错误描述。
Linux系统内核代码中errno的值及其对应的中文意思

/usr/include/asm/errno.h
#define EPERM 1 /* Operation not permitted */操作不允许
#define ENOENT 2 /* No such file or directory */文件/路径不存在
#define ESRCH 3 /* No such process */进程不存在
#define EINTR 4 /* Interrupted system call */中断的系统调用
#define EIO 5 /* I/O error */I/O错误
#define ENXIO 6 /* No such device or address */设备/地址不存在
#define E2BIG 7 /* Arg list too long */参数列表过长
#define ENOEXEC 8 /* Exec format error */执行格式错误
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值