当前位置:网站首页>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;
}
边栏推荐
- 2021-11-04
- With the deep integration of cloud platform, the "Xueba" objectscale in the object storage industry is coming
- Qt6 QML Book/Qt Quick 3D/Qt Quick 3D
- Salary management system based on servlet+jsp+mysql [source code + database]
- Explain the underlying principles of JVM garbage collection in simple terms
- Collinearity problem
- The new paradigm of AI landing is "hidden" in the next major upgrade of software infrastructure
- Stack implementation integrated Calculator - code implementation
- JS file block to Base64 text
- SQL server2005中SUM函数中条件筛选(IF)语法报错
猜你喜欢

在大厂外包呆了三年,颠覆了我的认知!

A solution to the problem of "couldn't open file /mnt/repodata/repomd.xml"

Five methods to clear floating and their advantages and disadvantages

AI落地的新范式,就“藏”在下一场软件基础设施的重大升级里

Use of thread pool

Configure specific source IP in SLA detection of FortiGate sdwan

Redis cache avalanche, breakdown and penetration

JS inheritance

Myrpc version 0

基于海康EhomeDemo工具排查公网部署出现的视频播放异常问题
随机推荐
errno和perror
Qt 6.3.1Conan软件包发布
Detailed explanation of data link layer
Find the interface and add parameters to the form
With the deep integration of cloud platform, the "Xueba" objectscale in the object storage industry is coming
基于ROS的SLAM建图、自动导航、避障(冰达机器人)
Internship: interface case implementation
JS generator
Idea grey screen problem
知识点滴 - 如何用3个简单的技巧在销售中建立融洽的关系
Clients accessing the daytime service (TCP)
股票利益【非dp】
Imile uses Zadig's multi cloud environment to deploy thousands of times a week to continuously deliver global business across clouds and regions
oslo_ config. cfg. ConfigFileParseError: Failed to parse /etc/glance/glance-api. Conf: a solution to errors
How to write a conditional statement to obtain the value of the maximum time in a table using a MySQL statement
Troubleshoot abnormal video playback problems in public network deployment based on Haikang ehomedemo tool
Unity 在编辑器中输入字符串时,转义字符的输入
FortiGate firewall configuration link detection link monitor and status query
Named pipes for interprocess communication
Qt6 QML Book/Qt Quick 3D/Qt Quick 3D