当前位置:网站首页>The C programming language (version 2) notes / 8 UNIX system interface / 8.3 open, create, close, unlink
The C programming language (version 2) notes / 8 UNIX system interface / 8.3 open, create, close, unlink
2022-06-12 16:27:00 【M rookie M】
8.3 open、creat、close、unlink
In addition to the default standard input 、 Standard output and standard error files , All other files must be opened explicitly before reading or writing
system call open and creat Used to realize this function
open With the first 7 This chapter discusses fopen be similar
The difference is , The former returns a file descriptor , It's just a int Type value , The latter returns a file pointer
If an error occurs ,open Will return -1
#include <fcntl.h>
int fd;
int open(char *name, int flags, int perms);
fd = open(name, flags, perms);
And fopen equally , Parameters name Is a string containing the file name
The second parameter flags It's a int Type value , It explains how to open the file , The main values are as follows :
O_RDONLY Open the file read-only
O_WRONLY Open the file in write only mode
O_RDWR Open the file read-write
stay System V UNIX In the system , These constants are in the header file <fcntl.h> In the definition of
And in the Berkeley(BSD) In version <sys/file.h> In the definition of
have access to fd = open(name, O_RDONLY, 0); Open a file to read
In the discussion of this chapter ,open Parameters of perms The value of is always 0
If you use open Open a file that doesn't exist , Will result in an error
have access to creat The system calls to create a new file or overwrite an existing old file , As shown below :
int creat(char *name, int perms);
fd = creat(name, perms);
If creat Successfully created the file , It will return a file descriptor , Otherwise return to -1
If this file already exists ,creat The length of this file will be truncated to 0, So as to discard the existing content
Use creat Creating an existing file does not cause an error
If the file to be created does not exist , be creat With the parameters perms Create a file with the specified permissions
stay UNIX File system , One for each file 9 Bit permission information
They control the of the file respectively owner 、 Owner group and The other members Reading of files 、 Write and perform access
therefore , Through one 3 The octal number of bits can easily explain different permissions
for example ,0755 Of a document owner You can read it 、 Write and perform operations , and Owner group and The other members Only read and execute operations
Here is a simplified UNIX Program cp explain creat Usage of
This program copies one file to another
This version we wrote can only copy one file , Directory is not allowed as the second parameter , also , The permissions of the target file are not obtained by copying , But redefined
#include <stdio.h>
#include <fcntl.h>
#include "syscalls.h"
#define PERMS 0666 /* RW for owner, group, others */
void error(char *, ...);
/* cp: copy f1 to f2 */
main(int argc, char *argv[])
{
int f1, f2, n;
char buf[BUFSIZ];
if (argc != 3)
error("Usage: cp from to");
if ((f1 = open(argv[1], O_RDONLY, 0)) == -1)
error("cp: can't open %s", argv[1]);
if ((f2 = creat(argv[2], PERMS)) == -1)
error("cp: can't create %s, mode %03o", argv[2], PERMS);
while ((n = read(f1, buf, BUFSIZ)) > 0)
if (write(f2, buf, n) != n)
error("cp: write error on file %s", argv[2]);
return 0;
}
The output file created by the program has fixed permissions 0666
utilize 8.6 To be discussed in section stat system call , You can get a schema of an existing file , And assign this pattern to its copy
Be careful , function error It's like a function printf, Variable length parameter table can be brought when calling
Pass below error The implementation of the function shows how to use printf Another member of the function family vprintf
Standard library functions vprintf Function and printf Function similar to , The difference is , It replaces the variable length parameter table with a parameter
And this parameter is set by calling va_start Macro initialization
Again ,vfprintf and vsprintf The functions are associated with fprintf and sprintf Function similar to
#include <stdio.h>
#include <stdarg.h>
/* error: print an error message and die */
void error(char *fmt, ...)
{
va_list args;
va_start(args, fmt);
fprintf(stderr, "error: ");
vprintf(stderr, fmt, args);
fprintf(stderr, "\n");
va_end(args);
exit(1);
}
There is a limit to the number of files a program can open at the same time ( Usually it is 20)
Accordingly , If a program needs to process many files at the same time , Then it must reuse the file descriptor
function close(int fd) Used to disconnect file descriptors from open files , And release this file descriptor , For other documents close Functions and... In the standard library fclose The function corresponds to , But it doesn't need cleaning (flush) buffer
If the program passes exit Function to exit or return from the main program , All open files will be closed
function unlink(char *name) Will file name Remove... From the file system , It corresponds to standard library functions remove
边栏推荐
- How to base on CCS_ V11 new tms320f28035 project
- Acwing 1927 自动补全(知识点:hash,二分,排序)
- JS monitors whether the user opens the screen focus
- "Shandong University project training" rendering engine system (8-END)
- acwing 800. 数组元素的目标和
- 借助SpotBugs将程序错误扼杀在摇篮中
- 使用 .NET 升级助手将NET Core 3.1项目升级为.NET 6
- Probation period and overtime compensation -- knowledge before and after entering the factory labor law
- The C Programming Language(第 2 版) 笔记 / 8 UNIX 系统接口 / 8.4 随机访问(lseek)
- The market share of packaged drinking water has been the first for eight consecutive years. How does this brand DTC continue to grow?
猜你喜欢

The market share of packaged drinking water has been the first for eight consecutive years. How does this brand DTC continue to grow?

acwing 802. 区间和 (离散化)

武汉大学甘菲课题组和南昌大学徐振江课题组联合招聘启事

Thinking about the probability of drawing cards in the duel link of game king

【研究】英文论文阅读——英语poor的研究人员的福利

acwing 800. Target and of array elements

Kill program errors in the cradle with spotbugs

C packing and unpacking

acwing 802. Interval sum (discretization)

pbootcms的if判断失效直接显示标签怎么回事?
随机推荐
Super detailed dry goods! Docker+pxc+haproxy build a MySQL Cluster with high availability and strong consistency
token与幂等性问题
Acwing 1927 自动补全(知识点:hash,二分,排序)
统计机器学习代码合集
线程池执行流程
Global and Chinese markets of automatic glue applicators 2022-2028: Research Report on technology, participants, trends, market size and share
WebRTC 的音频网络对抗概述
acwing 高精度乘法
calibration of sth
acwing 790. The cubic root of a number (floating-point number in half)
acwing 801. Number of 1 in binary (bit operation)
js監聽用戶是否打開屏幕焦點
Cookie 和 Session
Differences between SQL and NoSQL of mongodb series
Collect | 22 short videos to learn Adobe Illustrator paper graphic editing and typesetting
试用期、加班补偿———进厂前后需要了解的知识《劳动法》
33-【go】Golang sync.WaitGroup的用法—保证go协程执行完毕,主协程才退出
Batch --04--- moving components
批量--04---移动构件
leetcode-54. Spiral matrix JS