Linux file input / output stream

File open, file write, file read, file close, file cursor lseek, file create

The general process of a file is to open or create a document - edit the document - save the document - close the document. The api (Application Programming Interface) provided by liunx file operation includes open, write, read, close, lseek, create, etc.

File open

open header files and functions

// open header file
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//open function
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
//The open function returns the value, success returns the file descriptor, and error returns - 1
//Pathname: File pathname. Example ". / file1"
//flags:O_RDONLY read only 		 O_WRONLY write only 		 O_RDWR  	  Readable, writable and openable
//		O_CREAT creates a file if the open file does not exist.
// 		O_EXCL 	  If OCREAT is specified at the same time and the file already exists, open() will make an error and return - 1.	 
//		O_APPEND is added to the end of the file every time the file is written.
//		O_TRUNC deletes the original contents of the file.
//mode: 	 You must have used o in flags_ Creat flag, mode records the access rights of the file to be created.

Classification and weighted digital representation of mode

Macro representationmeaningMacro representationmeaningMacro representationmeaning
S_IRUSRUser readable permissionsS_IRGRPThe group has read permissionS_IROTHOther users have read permission
S_IWUSRUser writable permissionS_IWGRPThe group has write permissionS_IWOTHOther users have write permission
S_IXUSRUser executable rightsS_IXGRPThe group has execution permissionS_IXOTHOther users have execution permission

S_IRUSR,S_IWUSR,S_IXUSR is commonly used

Weighted numberfirst placeSecond placeThird place
4User readable permissionsThe group has read permissionOther users have read permission
2User writable permissionThe group has write permissionOther users have write permission
1User executable rightsThe group has execution permissionOther users have execution permission

For example: 0666, with 4 + 2 = 6 user readable and writable permissions; Have 4 + 2 = 6 group readable and writable permissions; Have 4 + 2 = 6 other user readable and writable permissions.

What is a file descriptor? In short, it is a sign to describe and distinguish files. As shown above, the file descriptor is of type int.
What is a program? What process?
1. Program is a static concept, GCC XXX C-o pro disk generates pro file, which is called program;
2. A process is a running activity of a program. Generally speaking, it means that when the program runs, there will be one more process in the system;
ps: in the figure, fd is the file descriptor. The process in the figure and the original process mean the same thing. In order to make the structure of the figure look clear, the name of the original process is taken.

Comprehensive example of open function:
int fd = open("./file1", O_RDWR|O_CREAT, 0600);open function synthesis example

File write

write header files and functions

// write header file
#include <unistd.h>;
//write function
ssize_t write(int fd, const void *buf, size_t count);
//Function meaning: write the number of count bytes from buf into fd file.
//Return success = number of bytes written; error returns - 1

Comprehensive example of write function:

	char *buf ="linux write";
	write(fd, buf, sizeof(buf));`write Function synthesis example`

File read

read header files and functions

// read header file
#include <unistd.h>;
//read function
ssize_t read(int fd, const void *readbuf, size_t count);
//Function meaning: read the number of count bytes from fd file and enter readbuf.
//Return success = number of bytes written; error returns - 1

read function synthesis example:

	read(fd, buf, sizeof(buf));`read Function synthesis example`

File close

close header files and functions

// close header file
#include <unistd.h>;
//read function
ssize_t close(int fd);
//Function meaning: close fd file.

Comprehensive example of close function:

	close(fd);`close Function synthesis example`

File cursor seek

After each reading or writing, the position of the cursor is uncertain. To determine the cursor position, you can use the lseek() function.
lseek header files and functions

// lseek header file
#include <unistd.h>;
#include <sys/type.h>;
//lseek function
off_t lseek(int fd, off_t offset, int whence);
//Function meaning: the number of bits of positioning offset offset according to where;
//whence: SEET_SET file header
//		  SEEK_CUR current cursor position
//		  SEEK_END end
//Offset: offset positive numbers move back and negative numbers move forward
//Return success returns the number of bytes offset between the current cursor position and the file header; Failure Return - 1

lseek function synthesis example:

	lseek(fd, 0, SEEK_END);`lseek Function synthesis example`

create file

create header files and functions

// Create header file
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//Create function
int creat(const char *pathname, mode_t mode);
//Function meaning: the number of bits of positioning offset offset according to where;
//Pathname: pathname of the file. Example ". / file1"
//Return success and return the file identifier; Failure Return - 1
Macro representationmeaning
S_IRUSRUser readable permissions
S_IWUSRUser writable permission
S_IXUSRUser executable rights
S_IRWXUUser readable, writable and executable rights

Comprehensive example of creat e function:

	creat(fd, S_IRWXU);`creat Function synthesis example`

Dynamic and static files

Static files are files that exist on disk.
Dynamic file means that after open ing the static file, the Linux kernel generates a structure, which contains the file identifier fd, information node, buf, etc., and then close to change back to the static file.

ps: compare the similarities and differences between the two programs vimdiff file name file name

Practical example 1: cp copy code writing

thinking
1. Open Src c
2. Read Src C to buf
3. Open des c
4. Write buf to des c
5. close two files

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)//argc is the total number of parameters on the command line
					//**argv=*argv [] is argc parameter, in which the 0th parameter is the full name of the program, and the subsequent parameters are the parameters entered by the user after the command line
{
        int fdSrc;//Open source file identifier
        int fdDec;//Open target file identifier

        if(argc !=3){
                printf("param error\n");
                exit(-1);
        } 			//Judge whether the input parameters are correct

        fdSrc=open(argv[1],O_RDWR,0600);

        int size = lseek(fdSrc,0,SEEK_END);  //Calculate file size
        lseek(fdSrc,0,SEEK_SET);			//Reset file cursor

        char *readBuf=(char* )malloc(sizeof(char)*size + 8);

        int n_read=read(fdSrc,readBuf,size);
        fdDec=open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0600);//Create readable, writable, executable, and delete the contents of the original file

        int n_write = write(fdDec,readBuf,size);

        close(fdSrc);
        close(fdDec);
        return 0;

}

Practical example 2: configuration file parameters

Idea:
1. Find the location of a
2. a moves back to b
3. Modify the contents of b

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
        int fdSrc;

        if(argc != 2){
                printf("param error\n");
                exit(-1);
        }

        fdSrc=open(argv[1],O_RDWR,0600);

        int size = lseek(fdSrc,0,SEEK_END);
        lseek(fdSrc,0,SEEK_SET);

        char *readBuf=(char* )malloc(sizeof(char)*size + 8);

        int n_read=read(fdSrc,readBuf,size);
        char *p = strstr(readBuf,"LENG=");//String lookup function
        if(p==NULL){
                printf("not found\n");
        }
        p=p+strlen("LENG=");			//String calculation function
        *p='5';

        lseek(fdSrc,0,SEEK_SET);
        int n_write = write(fdSrc,readBuf,size);

        close(fdSrc);
        return 0;

}

Expanding knowledge -- comparing the differences between fopen series and open series functions

1. Source
open is a UNIX system call function (including LINUX, etc.) and returns a File Descriptor, which is the index of the file in the File Descriptor table.
fopen is a C language library function in ANSIC standard. Different kernel APIs should be called in different systems. Returns a pointer to the file structure.
2. Transplantability
fopen is a C standard function, so it has good portability; open is a UNIX system call with limited portability. For similar functions under windows, use the API function CreateFile.
3. Scope of application
open returns the file descriptor, which is an important concept in UNIX system. All devices in UNIX operate in the form of files. Of course, it includes the operation of regular files. fopen is used to manipulate regular files.
4. File IO hierarchy
The simple distinction between low-level and high-level is: who is closer to the system kernel. Low level file IO runs in kernel mode and high-level file IO runs in user mode. open is a low-level IO function and fopen is a high-level IO function.
5. Buffer
The characteristics of buffer file system are: opening a "buffer" in memory for each file in the program; When reading a file, read the data from the disk file into the memory "buffer", fill it up, and then read the required data from the memory "buffer". When writing a file, write the data into the memory "buffer" first, and then write the file after the memory "buffer" is full.
Unbuffered file system depends on the operating system. It reads and writes files through the functions of the operating system. It is a system level input and output. It does not set a file structure pointer and can only read and write binary files, but it has high efficiency and high speed.
In short. Buffer file system needs buffer conversion, and non buffer file system directly realizes the conversion between kernel state and user state. At present, the memory is relatively large, and there is little difference between the running speed of the two modes.
fopen header files and functions
Header file: #include < stdio h>
Function: FILE *fopen(const char *path, const char *mode);
Freead and fwrite header files and functions
Header file: #include < stdio h>
Function: size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
Function: size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
Fseek and fseek header files and functions
Header file: #include < stdio h>
Function: int fseek (file * stream, long offset, int where);
Parameter interpretation
void *ptr: pointer to the element array to be read (written)
size_t size: the size of the element array to be read (written), in bytes
size_t nmemb: number of elements, in size
FILE *stream: pointer to FILE object
This is the end. The teacher inherits the superior's programmability;

Keywords: Linux Embedded system Operating System

Added by danielholmes85 on Sun, 20 Feb 2022 09:19:05 +0200