File IO foundation under linux

2019-09-23

Keywords: stream Linux file types, Linux file IO, Linux standard IO, C language


 

The nature of the file is a collection of data. Computers in everyday life are almost always be used in processing the data area. In linux operating system, everything will be considered "documents."

 

1, common file types

 

Linux common file types and their identifiers have the following seven:

1, the conventional file: -

2, catalog file: d

3, character device file: c

A special file, representing a device. Such as: keyboard, mouse, video cameras.

4, block device file: b

 And above character device files, it is used to map represents an external device. The distinction between block character device file with the file size is different when transferring data. File is a fixed length block device to transmit data, and the character device file is of indefinite length.

5, pipe file: p

Generally used for inter-process communication.

6, the socket file: s

Generally used for inter-process communication. Both network communication, local communication can be achieved.

7, symbolic link files: l

Similar to the quick link. Soft and hard links sub links two kinds.

 

2, file IO basic concepts

 

Bare metal development :

Code to directly access the hardware development model called "naked machine development." In other words, the bare metal generally refers to the development of software development model developed in the case where no operating system. Likewise, the concept can be extended "bare metal" refers to the hardware device system without an operating system.

 

System call :

The above development with the corresponding bare metal, another operation mode is the first hardware through the operating system. The operating system will encapsulate all the hardware resources, the application does not allow direct manipulation, but some open interfaces to the application called indirectly via the operating system to control hardware devices. These open out by the operating system interface is used to control the hardware is called " system calls ." From another perspective, the hardware operating system package can play a protective role.

 

3, the IO standard

 

Standard IO library is available to support the general operation of the application file. It is defined by the ANSI C standard. IO standard has been implemented on all major operating systems, so it's a good compatibility. Standard IO encapsulated into the files FILE structure, also known as "flow." Strictly speaking stream need to distinguish between "binary stream" and "text flow." Because the communication operating system and hardware devices that requires some resource overhead, in order to enhance operational efficiency, resource conservation, setting the standard IO buffer mechanism. It refers to a so-called buffer when an application is reading or writing, data is temporarily stored in memory first, when reached after a predetermined condition with the data communication with the hardware.

Standard IO buffer mechanism in three ways:

1, the whole buffer;

All IO data is temporarily stored in memory until a given memory space is exhausted before the actual occurrence of the system call.

2, line buffer;

All the IO data is buffered into memory until it encounters '\ n' character before the actual occurrence of the system call. Our standard input and output (scanf (), printf ()) is the row buffer mode, as long as there is no newline when you call, have been the data cached in memory until the program ends. We sometimes encounter block error occurs during operation, some print without playing out before the error, and this is because they want to print data is cached in memory, and encountered while waiting in line breaks mistakes forced to quit, has led to the print information did not break out.

3, unbuffered.

If that.

 

Standard booked three IO streams, they will automatically open when the program runs, the process of their names and numbers are:

1, the standard input stream: 0: STDIN_FILENO: stdin

2, the standard output stream: 1: STDOUT_FILENO: stdout

3, the standard error stream: 2: STDERR_FILENO: stderr

 

IO standard operating mode of the file stream:

Open a stream:

FILE *fopen(const char *path, const char *mode);

 

Use file permissions fopen created default is 0666, but the actual generation of the file permissions also take into account the Linux umask before the final decision.

 

Close a stream:

int fclose(FILE *stream);

When closed successfully returns the value 0. Otherwise it returns EOF, and set the errno.

Fclose executed when a stream, it will automatically all the data in the cache are flushed to the corresponding hardware, and release the buffer.

When a program terminates normally, it will automatically close all open streams.

 

Processing error stream:

IO standard in a predefined integer variable is used to indicate different types of errors, it is an integer variable errno. If we need to reference in the application to the errno, you can make the following statement:

extern int errno;

There may be a printing error message output function interface: void perror (const char * msg); This function first print parameters msg, and then printing the current errno its corresponding error message. It can be said that the error indication weapon.

There is also a function that returns the specified error number represents the meaning: char * strerror (int errno);

 

Standard IO stream of objects in the operating mode:

The so-called stream of objects is actually operating according to the established format to read or write data from the stream. We established this format can be simply understood achievement is a custom structure. It can be easily read and write data from the stream in any way by this demand.

 

This operation target stream function mainly two:

size_t fread(void *ptr, size_t size, size_t n, FILE *fp);

size_t fwrite(const void *ptr, size_t size, size_t n, FILE *fp);

These two functions are only the second and third parameters explain yourself. The second argument is that by our custom, "structure", in fact, is meant to be a number of bytes of data read. Generally used sizeof (xxx) instead. The third argument is that we hope that the number of data size_t read, usually sizeof (xxx) * n instead. Both functions return value is the actual amount of data read or written, i.e., the actual number of read and write data size_t bytes. When a write error is returned EOF, returns 0 when the reader reaches the end.

 

Flush the stream:

Mentioned earlier, input and output are standard IO buffer mechanism, only the actual system calls the process will occur when the flow of data to achieve the established conditions. But the standard IO also provides supply manually program the data in the buffer flushed to interface system call. It is

int fflush(FILE *fp);

When we call this function, the data in the write buffer will be immediately flushed to the system call to go. The return value 0:00 flashing succeeds, the return value is EOF on failure. Also note that this is only valid for writing brush write buffer.

 

If we have to refresh the buffer is read, you can read the address to a useless consumption curve out to achieve by fgetc function.

 

Positioning stream:

IO standard functions provided for positioning three streams:

long ftell(FILE *stream);

long fseek(FILE *stream, long offset, int whence);

long rewind(FILE *stream);

ftell Returns the specified stream is read the current position.

Fseek read position specified flow sucked into whence position for positioning at a position offset drift. whence parameter where you can fill in any integer, you can also use standard IO available in three macros: SEEK_SET, SEEK_CUR, SEEK_END. These three macros are representing the starting position of the stream, the end of the current position of the stream, the stream. offset can be positive or negative, to control the forward backward offset.

It is to write the position specifying rewind stream positioned directly to the starting position.

 

Detecting flow:

IO standard provides two functions for a specific application determines whether an error or the end of the stream.

int ferror(FILE *steam);

int feof(FILE *stream);

Both functions return value is a "logical value", represents a logical TRUE, the return value of 0 indicates a logic value 1 when the return false.

 

Formatted output:

int printf(const char *fmt, ...);

int fprintf(FILE *stream, const char *fmt, ...);

int sprintf(char *s, const char *fmt, ...);

The most common of the first function, the output format of the specified string to the standard output stream.

The second function is actually an upgraded version of the first function, it handed over control of the output stream applications to decide. Its role is to output the formatted string to the specified stream.

Third function sucked formatted string to the output string memory.

 

4, file IO

 

File IO is a broader IO interface. File IO POSIX is a set of functions to follow protocol, which uses a wider range, can support a variety of file formats. The core concept of file IO is "file descriptor" that fd.

 

On Linux systems, standard file IO IO only a branch of it.

 

File IO interface are encapsulated in the fcntl.h.

 

To open stream:

int open(const char *path, int flags, ...);

Returns the file descriptor when opening success. Returns EOF on error.

The parameters of this function is variable, the number of parameters is 2 or 3. When opening a file, only you need to use the first two parameters. When you create a file, you need to use three parameters.

flags parameter typically using a macro defined in the interface, optional types:

O_RDONLY: Read-only

O_WRONLY: Write only

O_RDWR: read and write

O_CREAT: If the file does not exist to create a new file. The third parameter must be filled out when using this parameter.

O_EXCL: used to test whether a specified file exists. Usually used in conjunction with O_CREATE. When a new document file already exists, an error message will errno set.

O_NOCTTY : 

O_TRUNC: If the file already exists, when you open first delete the existing data.

O_APPEND: added.

The third parameter is an integer, notation used to represent file permissions, such as 0666, 0777, 0755 and so on.

 

Close the stream:

int close(int fd);

The return value 0:00 succeeds, the return value is EOF on failure.

 

Read and write streams:

#include <unistd.h>

ssize_t read(int fd, void *buf, size_t count);

Not explained. The return value is the number of bytes successfully read. When read indicates the end of the return value is zero. Returns EOF on error.

 

#include <unistd.h>

ssize_t write(int fd, void *buf, size_t count);

Not explained.

 

Positioning:

#include <unistd.h>

off_t lseek(int fd, off_t offset, intt whence);

IO standard in locating similar interface. This function is the positioning of the current position of the reader. Return is to specify the current location of the file descriptor to read and write at the time of execution success. Returns EOF on error.

 

Access the catalog:

#include <dirent.h>

DIR *opendir(const char *path);

DIR is a structure type, is described in the catalog file open type. Success is returned when opening the appropriate directory stream pointer, when a failure is returned NULL.

 

#include <dirent.h>

struct dirent * readdir (DIR * dirp);

Read the contents of a directory. Success is returned when the execution directory entries. This function returns only once a directory entry, which means that typically need to call this function repeatedly in a loop until the function represents read all the contents of the directory only return NULL.

 

#include <dirent.h>

int closedir(DIR *dirp);

No explanation.

 

Access to modify the file:

#include <sys/stat.h>

int chmod(const char *path, mode_t mode);

int fchmod(int fd, mode_t mode);

It features two functions exactly the same. Modify access are specified file.

 

Get the properties file:

#include <sys/stat.h>

int stat(const char *path, struct stat *buf);

int lstat(const char *path, struct stat *buf);

int fstat(int fd, struct stat *buf);

The first function returns the actual file attributes, that is, if the incoming file is a symbolic link, then the return of the properties of this real file the symbolic link points.

The second function can return a symbolic link property itself, of course, you can get the general properties of the file.

The third function is the first function the same, but different usage.

 

About struct stat structure:

It is specific to structural type of store file attributes. Its structure members are:

mode_t st_mode - the type used to store and access rights.

uid_t st_uid - ID of the file owner.

uid_t st_git - ID file owner belongs.

off_t st_size - size of the file.

time_t st_mtime - time of last modification.

...

 

About file types mode_t structure:

This structure is a 32-bit integer variables. Records on file types should be calculated according to the following rules:

st_mode & 0170000

S_ISREG -- 0100000

S_ISDIR -- 0040000

S_ISCHR -- 0020000

S_ISBLK -- 0060000

S_ISFIFO -- 0010000

S_ISLNK -- 0120000

S_ISSOCK -- 0140000

 

File access permissions are stored in the lower 8 bits.

 


 

Guess you like

Origin www.cnblogs.com/chorm590/p/11565956.html