当前位置:网站首页>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;
}
边栏推荐
- The innovation consortium of Haihe laboratory established gbase and became one of the first member units of the innovation Consortium (Xinchuang)
- 第04天-文件IO
- Use redis' sorted set to make weekly hot Reviews
- Listen to the markdown file and hot update next JS page
- 天书夜读笔记——反汇编引擎xde32
- sql 聚合函数有哪些
- Reverse ordinal number by merge sort
- pbcms添加循环数字标签
- 音频PCM数据计算声音分贝值,实现简单VAD功能
- Bi-sql create
猜你喜欢

Assembly language (4) function transfer parameters
![最长连续序列[扩散法+空间换时间]](/img/db/7b0d1b0db7015e887340723505153a.png)
最长连续序列[扩散法+空间换时间]

同一服务器两个端口不同的应用session覆盖解决方案

How to store dataframe data in pandas into MySQL

Bi-sql between

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

AUTOCAD——两种延伸方式

Bi-sql Union

Q1季度逆势增长的华为笔电,正引领PC进入“智慧办公”时代

Ps5 connected to oppo K9 TV does not support 2160p/4k
随机推荐
Basic knowledge of assembly language (2) -debug
PHP easywechat and applet realize long-term subscription message push
Powerbi - for you who are learning
php中preg_replace如何替换变量数据
Multi modal data can also be Mae? Berkeley & Google proposed m3ae to conduct Mae on image and text data! The optimal masking rate can reach 75%, significantly higher than 15% of Bert
脱氧核糖核酸酶I中英文说明书
Deoxyribonuclease I instructions in Chinese and English
15. several methods of thread synchronization
IPC mechanism
ICML2022 | 用神经控制微分方程建立反事实结果的连续时间模型
Expectation and variance
安超云:“一云多芯”支持国家信创政务云落地
2种常见的设备稼动率OEE监测方法
RedisTemplate操作Redis,这一篇文章就够了(一)[通俗易懂]
php easywechat 和 小程序 实现 长久订阅消息推送
动手学数据分析 数据建模和模型评估
After the college entrance examination, the following four situations will inevitably occur:
Bi-sql top
Redis persistence
excel 汉字转拼音「建议收藏」