当前位置:网站首页>Day 04 - file IO
Day 04 - file IO
2022-06-25 01:37:00 【Worth the trip -rui】
The first 04 God - file IO


01. Introduction and implementation of system call
system call Is a controlled kernel entry , With the help of this mechanism , A process can request the kernel to perform certain actions in its own name
** Realization :** System calls are part of the operating system kernel , Processes must be provided in some way to call .
CPU Can run at different privilege levels , And the corresponding operating system also has some running levels ( User mode and kernel mode ) Processes running in kernel mode can access all kinds of resources without restriction ,
The operating system passes through Software interrupt Switch from user state to kernel state
02. The difference between system calls and library functions
Library function :[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-18xZd0AJ-1656067116776)(D:\ picture \image-20220624082305545.png)]
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-jUqNl4V0-1656067116778)(D:\ picture \image-20220624083042666.png)]
03. Error handling functions
errno Is the last error code of the recording system , The code is a int type , stay errno.h In the definition of . When Linux C API When an exception occurs to a function , Generally, they will
errno Assign an integer value to a global variable , Different values mean different things ,
#include<stdio.h>
#include<errno.h>
#include<string.h>
int main()
{
FILE *fp=fopen("txt","r");
if(NULL==fp)
{
printf("%d\n",errno);// Print error code
printf("%s\n",strerror(errno));
perror("fopen err");
}
return 0;
}
result :
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-QRKb6Lfs-1656067116778)(D:\ picture \image-20220624091815191.png)]
Part of the information represented by the return value
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-zuq2frC9-1656067116779)(D:\ picture \image-20220624092904783.png)]
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-tcsGb7zO-1656067116779)(D:\ picture \image-20220624093031088.png)]
04. Virtual address space
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-7SbINfYi-1656067116780)(D:\ picture \image-20220624093903228.png)]
05. File descriptor
When opening an existing file or creating a new file , The system will return a file descriptor , Used to specify open files . Equivalent to label ( The operation file descriptor is equivalent to the file specified in the operation description )
The program runs with a table of file descriptors , The standard input , Output , Error output device file opened , The corresponding file descriptor 0,1,2 Record in a table , It is turned on by default .
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-tfhpJDwa-1656067116780)(D:\ picture \image-20220624105334278.png)]
06. file IO function
open function :
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
function :
Open file , If the file exists, you can choose to create
Parameters :
pathname: File path and file name
flags: Open file behavior flag , Will options O_RDONLY( read-only ),O_WRONLY( Just write ),O_RDWR( Can be read , Can write )
mode: This parameter , Only valid if the file does not exist , It refers to the permission of the specified file when creating a new file
Return value :
success : Successfully returned open file descriptor
Failure :-1
flags Detailed instructions
Mandatory
- O_RDONLY— read-only
- O_WRONLY— Just write
- O_RDWR— Can be read , Can write
optional , And the required options are bitwise OR
O_CREAT If the file does not exist, create the file , Use... When using this option mode Describe the permissions of the file
O_EXCL If you also specify O_CREAT, And the file already exists , You make a mistake
O_TRUNC If the file exists , Then clear the contents of the file
O_APPEND When writing files , Add data to the end of the file
O_NONBLOCK For device files , With O_NONBLOCK Mode open can do non blocking i/o
mode Additional explanation
1) Final file permissions :mode & -umask
2)shell Process umask The mask can be used umask Command view
umask: Look at the mask
umask mode: Set mask ,mode It's octal
umask -S: View the default operation permissions of each group of users
close function
#include<unistd.h>
int close(int fd)
function :
Close open files
Parameters :
fd: File descriptor ,open() The return value of
Return value :
success :0
Failure : -1, And set up errno
open and close Example :
// Open in write only mode , If present, open , If the file does not exist, create it directly
//fp=open("txt",O_WRONLY|O_CREAT,0644);
// If the file exists, an error is reported , Create if it does not exist
//fp=open("txt",O_WRONLY|O_CREAT|O_EXCL,0644);
//O_TRUNC Empty file contents
// Created if it does not exist , Empty after opening if any
//fp=open("txt",O_WRONLY|O_TRUNC|O_CREAT,0644);
//O_APPEND
// Open a file in write only and append mode , If the file does not exist, an error will be reported
//fp=open("txt",O_WRONLY|O_APPEND);
//
if(fp==-1)
{
perror("open");
return 1;
}
printf("fp=%d\n",fp);
close(fp);
return 0;
}
write function
#include<unistd.h>
ssize_t write(int fd,const void *buf,size_t count)
function : Write a specified number of data to a file
Parameters :
fd: File descriptor
buf: First address of data
count: Length of data written
Return value :
success : Number of bytes actually written to data
Failure :-1
Example :
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
int main(void){
//1. Open in write only mode , If not, create
int fp=-1;
char *str="hello word";
fp=open("txt",O_WRONLY|O_CREAT,0644);
if(fp==-1)
{
perror("open");
return 1;
}
int ret=0;
// Writing documents
ret=write(fp,str,strlen(str));
if(ret==-1)
{
perror("write");
return 2;
}
printf("ret=%d\n",ret);
//3. Close file
close(fp);
return 0;}
read function :
#include<unistd.h>
ssize_t read(int fp,void *buf,size_t count)
function :
Read a specified number of data into memory ( buffer )
Parameters :
fp: File descriptor
buf: Memory head address
count: Number of bytes read
Return value :
success : The number of bytes actually read
Failure :-1
int fp=-1;
char buf[128];
fp=open("txt",O_RDONLY);
if(fp==-1)
{
perror("open");
return 1;
}
int ret=0;
// Reading documents
// From file descriptor fp The maximum number of reads in size Save bytes to buf in , The actual number of bytes read is returned by the return value
ret=read(fp,buf,128);
if(ret==-1)
{
perror("read");
return 2;
}
printf("ret=%d,len=%s\n",ret,buf);
//3. Close file
close(fp);
return 0;}
07. Blocking and non blocking
Reading regular files doesn't block , No matter how many bytes are read ,read Must return in a limited time ,
Reading from a terminal device or network is not necessarily , If the data input from the terminal has no newline character , call read Reading the terminal device will block , If there is no data, it will be blocked all the time .
lseek function
#incldue<sys/types.h>
#include<unistd.h>
off_t lseek(int fd,off_t offset,int whence);
function :
Change the offset of the file
Parameters :
fd: File descriptor
offset: according to whence The number of displacements to move , The positive number moves right , Negative numbers move left , If it exceeds the beginning of the file, an error will be returned , If you move backward past the end of the file , Writing again will increase the file size .
whence: Its value is as follows :
SEEK_SET: Move from the beginning offset Bytes
SEEK_CUR: Move... From the current position offset Bytes
SEEK_END: Move from the end of the file offset Bytes
Return value :
if lseek Successful execution , Returns a new offset
If you fail , return -1
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main()
{
int fd=-1;
int ret=-1;
char buf[128];
//1. Open file
fd=open("txt",O_RDWR|O_CREAT,0644);
if(fd==-1)
{
perror("open");
return 1;
}
//2.lseek Add write
write(fd,"sundengrui",10);
ret=lseek(fd,32,SEEK_SET);
if(-1==ret)
{
perror("lseek");
return -1;
}
write(fd,"12345678",9);
// Point the file location pointer to the beginning
lseek(fd,0,SEEK_SET);
memset(buf,0,128);
ret=read(fd,buf,128);
printf("ret:%d\n,buf:%s\n",ret,buf);
//3. Close file
close(fd);
return 0;
}
ror(“lseek”);
return -1;
}
write(fd,“12345678”,9);
// Point the file location pointer to the beginning
lseek(fd,0,SEEK_SET);
memset(buf,0,128);
ret=read(fd,buf,128);
printf(“ret:%d\n,buf:%s\n”,ret,buf);
//3. Close file
close(fd);
return 0;
}
边栏推荐
- Bi-sql like
- pbcms添加循环数字标签
- php easywechat 和 小程序 实现 长久订阅消息推送
- IPC机制
- (CVPR 2020) Learning Object Bounding Boxes for 3D Instance Segmentation on Point Clouds
- Elastase instructions in Chinese and English
- 在两个有序数组中找到整体第K小的数可以做到O(log(Min(M,N)))
- This national day! Tencent cloud wecity will accompany you to travel and light up the city landmark
- Tianshu night reading notes -- disassembly engine xde32
- 带马尔科夫切换的正向随机微分方程数值格式模拟
猜你喜欢

Reading notes at night -- deep into virtual function

新一代可级联的以太网远程I/O数据采集模块

Deep learning LSTM model for stock analysis and prediction

数组中关于sizeof()和strlen

实验5 8254定时/计数器应用实验【微机原理】【实验】

Ps5 connected to oppo K9 TV does not support 2160p/4k
![uni-app集成极光推送插件后真机调试提示“当前运行的基座不包含原生插件[JG-JPush]...”问题的解决办法](/img/8b/0e982711c225ec8b0a2b90819d8a11.png)
uni-app集成极光推送插件后真机调试提示“当前运行的基座不包含原生插件[JG-JPush]...”问题的解决办法

明日考试 最后一天如何备考?二造考点攻略全整理

谷歌浏览器控制台 f12怎么设置成中文/英文 切换方法,一定要看到最后!!!

Bi-sql - different join
随机推荐
Redis persistence
1. 封装自己的脚手架 2.创建代码模块
pbcms添加循环数字标签
脱氧核糖核酸酶I中英文说明书
高考之后,必然会出现以下四种情况:
音频PCM数据计算声音分贝值,实现简单VAD功能
Unity C# 网络学习(六)——FTP(二)
字符串常用方法
修身励学篇
Bi-sql like
Chinese and English instructions of Papain
Redis and jedis
Introduction to bi-sql wildcards
AUTOCAD——两种延伸方式
Using macro code to generate handwriting automatically in word or WPS
天书夜读笔记——深入虚函数virtual
Bi SQL drop & alter
Deep learning LSTM model for stock analysis and prediction
Abnova丨5-甲基胞嘧啶多克隆抗体中英文说明
Elastase instructions in Chinese and English