当前位置:网站首页>File and IO
File and IO
2022-06-30 04:25:00 【Tra220123】
1.open function
You can open or create a file .

Return value : Successfully returned the newly allocated file descriptor , Error return -1 And set up errno
pathname: The name of the file opened or created , Is a relative path or Absolute path .
flags: Multiple constants can be selected at the same time and connected by bitwise OR operator , Macro definitions are based on O_ start , Express or.


#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("usage: cmd filename\n");
return -1;
}
int fd = open(argv[1], O_WRONLY | O_CREAT, 0644);
if (fd < 0) {
perror("OPEN");
return -1;
}
return 0;
}2.close function
Close an open file .

fd: Closed file descriptor . When a process terminates , The kernel calls all file descriptors of the process that have not been closed close close , So even if the user program doesn't call close, On termination, the kernel will also automatically close all files it opens .
from open The returned file descriptor must be the smallest descriptor that the process has not yet used .
3.read function
Read data from an open device or file .

count: Number of bytes requested to read , The read data is stored in the buffer , At the same time, the current read-write position of the file moves backward .
Be careful : This read / write location and use C standard I/O The read / write location of the library may be different , This read / write location is recorded in the kernel , While using C standard I/O The read / write location of the library is user space I/O Buffer location .
There are some cases , The number of bytes actually read will be less than the number of bytes requested . Such as :
① When reading a regular file , Reading count The end of the file was reached before bytes .
② Read from the terminal device , Usually in behavioral units , Read the newline character and return .
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
char buf[20];
int n = read(STDIN_FILENO, buf, 10);
if (n < 0) {
perror("READ STDIN");
exit(1);
}
printf("read %d bytes\n", n);
for (int i = 0; i < n; i++) {
printf("%c", buf[i]);
}
putchar(10);
close(n);
return 0;
}4.write function
Write data to open settings or files

5. Blocking and non blocking
Blocking : When a process calls a blocked system function , The process is placed in Sleep state , At this time, the kernel schedules other processes to run , Until the event that the process is waiting for happens ( Such as : Packet received on the network , call sleep The specified sleep time has expired ) It is possible to continue to run .
sleep The opposite is running state . stay linux The kernel , There are two kinds of running processes :
① Is being scheduled to execute :CPU In the context of the process , Program counter (eip) Save the instruction address of the process , Executing instructions for the process , Reading and writing the address space of the process .
② Ready state : The process doesn't have to wait for something to happen , Ready to execute , but CPU Another process is in progress for the time being , All the processes are in a ready queue waiting to be dispatched by the kernel .
If in open A setting specifies O_NONBLOCK sign ,read/write It won't block .
With read For example , If the device has no data to read for the time being, return 1, notice errno by EWOULDBLOCK, It means that it should have been blocked here , In fact, it doesn't block, it just returns an error , The caller should try to read it again , This is called polling . The caller just looks up , Instead of waiting here to die , This allows multiple devices to be monitored at the same time .

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
int fd = open("/dev/tty", O_RDONLY | O_NONBLOCK);
if (fd < 0) {
perror("OPEN /dev/tty");
exit(1);
}
int n;
char buf[10];
int cnt=10;
while (cnt>0) {
n = read(fd, buf, 10);
if (~n) {
printf("read %d bytes\n", n);
write(STDOUT_FILENO, buf, n);
break;
}
if (errno != EAGAIN) {
perror("READ /dev/tty");
exit(1);
}
write(STDOUT_FILENO, "try try?\n", 9);
sleep(1);
cnt--;
}
close(fd);
return 0;
}6.Iseek
Each open file records the current read / write location , When opening a file, the read / write location is 0, Indicates the beginning of the file , Usually, the number of bytes read and write will move the read and write position back by as many bytes .
except O_APPEND open , Each write operation appends data to the end of the file , Then move the read / write position to the end of the new file .

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
int fd;
if ((fd=open("./test.txt", O_RDONLY)) < 0) {
perror("OPEN");
exit(1);
}
char c;
read(fd, &c, 1);
write(STDOUT_FILENO, &c, 1);
int pos = lseek(fd, 3, SEEK_CUR);
read(fd, &c, 1);
write(STDOUT_FILENO, &c, 1);
printf("\npos=%d\n", pos);
close(fd);
return 0;
}7.fcntl
use fcntl Function to change the properties of an open file without having to re open file , Read can be reset 、 Write 、 Additional 、 Non blocking and other signs .

except F_GETFL,F_SETFL Besides the command ,fcntl And hahndou orders other operations , Such as : Set file record lock .
Can pass fcntl It sets the access control properties of how the current process accesses the device or file .
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
int flags;
if ((flags = fcntl(STDIN_FILENO, F_GETFL)) < 0) {
perror("fcntl get flags");
exit(1);
}
flags |= O_NONBLOCK;
if ((flags = fcntl(STDIN_FILENO, F_SETFL, flags)) < 0) {
perror("fcntl set flags");
exit(1);
}
char buf[10];
ssize_t n;
while (1) {
n = read(0, buf, 5);
if (n >= 0) break;
if (errno != EAGAIN) {
perror("read");
exit(1);
}
write(1, "try again?\n", 11);
sleep(1);
}
write(1, buf, n);
return 0;
}8.ioctl
It is used to send control and configuration commands to the equipment

d: A file descriptor for a device .
request:ioctl command , Variable parameters depend on request, Usually a pointer to a variable or pointer body .
Return in case of error -1, If successful, other values will be returned , The return value also depends on request.
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
int main(void) {
struct winsize size;
if (!isatty(1)) {
printf("1 is not tty\n");
exit(1);
}
if (ioctl(1, TIOCGWINSZ, &size) < 0) {
perror("ioctl");
exit(1);
}
printf("%d rows, %d columns\n", size.ws_row, size.ws_col);
return 0;
}
边栏推荐
- 技术分享| 融合调度中的广播功能设计
- JS proxy
- 【WEBRTC】ADM: rtc_include_internal_audio_device 触发 RTC_DCHECK(adm) 断言
- FortiGate firewall filters the specified session and cleans it up
- Create thread in callable mode
- After the win10 system uses the browser to download, the content is moved or deleted without reason
- Qt Creator 8 Beta2发布
- idea灰屏问题
- What is the difference between synchronized and lock
- Daily summary of code knowledge
猜你喜欢

el-upload上傳文件(手動上傳,自動上傳,上傳進度)

Day 12 advanced programming techniques

OneNote software

Huawei cloud native - data development and datafactory

进程间通信之匿名管道

Junior students summarize JS advanced interview questions
![Salary management system based on servlet+jsp+mysql [source code + database]](/img/4a/6015cf17f4297691e97b48a5592fc5.png)
Salary management system based on servlet+jsp+mysql [source code + database]

lego_loam 代码阅读与总结

How to use div boxes to simulate line triangles

Day 11 script and game AI
随机推荐
Share an example of a simple MapReduce method using a virtual machine
Clients accessing the daytime service (TCP)
【WEBRTC】ADM: rtc_ include_ internal_ audio_ Device triggers RTC_ Dcheck (ADM) assertion
win10系统使用浏览器下载后,内容无故移动或删除
两个月拿到N个offer,什么难搞的面试官在我这里都不算事
Unity 在编辑器中输入字符串时,转义字符的输入
Myrpc version 5
mysql更新数组形式的json串
Implementation steps of dynamic proxy
Stack implementation integrated Calculator - code implementation
SQL append field
lego_loam 代码阅读与总结
Es2017 key summary
Salary management system based on servlet+jsp+mysql [source code + database]
输入输出及中断技术——微机第六章学习笔记
知识点滴 - 如何用3个简单的技巧在销售中建立融洽的关系
Qt 6.3.1Conan软件包发布
An error occurs when sqlyog imports the database. Please help solve it!
RPC correction based on arcpy API
Huawei cloud native - data development and datafactory