Linux Programming--File Operations (chapter III)

Source: Internet
Author: User
Tags fread truncated

Chapter III File operations
3.1 Linux file structure like Unix, files in a Linux environment are particularly important because they provide a simple and consistent interface for operating system services and devices. In Linux, everything is a file.
This means that the program can typically use disk files, serial ports, printers, and so on, as with files.
A directory is also a file, but it is a special type of file. In modern Unix (including Linux) versions, even super users may no longer be allowed to write left-to-do directories directly. All users typically use the upper-level Opendir/readdir interface to read the directory without needing to know the specifics of the directory implementation in a particular system.
The 3.1.1 directory file, in addition to its own content, has a name and some attributes, namely "management information", including the creation/modification date and its access rights. These attributes are saved in the file love your Inode (node), which is a special data block in the file system, it also contains the length of the file and the location of the file on the disk. The system uses the inode number of the file, and the directory structure is named for the file only for ease of use by people.
A directory is a file that holds the node number and name of other files. Each data item in the catalog file is a link to a file node, and deleting the file name is equivalent to deleting the corresponding link. The node number of the file is viewed through the ln-i command.
When you delete a file, you essentially delete the directory entry for that file, and the number of links to that file is reduced by 1. The data in the file may still be accessible through other links to the same file. If the number of links to a file becomes 0, it means that the node and the data it points to are no longer in use, and the corresponding location on the disk is marked as free space.
The root directory typically contains the/bin for the System program (binary executable), the/etc for the system configuration file, and the/lib for storing the system function library. Files that represent physical devices that do not provide an interface to these devices are typically stored in/dev.
3.1.2 Files and device hardware devices are also usually represented in Linux (maps) for files.
There are 3 more important device files in Unix and Linux:/dev/console,/dev/tty and/dev/null.
1./dev/console
The system console, error messages, and diagnostic information are usually sent to this device.
2./dev/tty
If a process has a control terminal, then the special file/dev/tty is the alias of this control terminal.
Although there is only one/dev/console device, there are many different physical devices that can be accessed through/dev/tty.
3./dev/null
The/dev/null file is an empty device. All output written to this file will be discarded, and reading the device will immediately return a file tail flag, so it can be used as a source file for copying empty files in the CP command.
Another way to create an empty file is to use the Touch <filename> command, which changes the file's modification time and creates it if the specified file does not exist, but the command does not turn the contents of the file into an empty file.
3.2 System calls and device drivers can access and control files and devices in a small number of functions, called system calls, which are provided directly by UNIX and are also interfaces to the operating system itself.
The core part of the operating system, the kernel, is a set of device drivers. They are a set of lower-level interfaces that control system hardware. For example, the tape drive has a corresponding device driver that knows if the tape is started, if it wraps around it, how to read and write to it, and so on, because the tape is a sequential access device, the driver does not have direct access to the data block on the tape, but must wrap it around the correct location.
In order to provide a consistent interface to the user, the device driver encapsulates all hardware-related features, and the unique features of the hardware are usually system-based via the IOCTL system.
The following is the underlying function for accessing the device driver (System call)
Open file or device
Read reading data from an open file or device
Write writes data to a file or device
Close files or devices
The IOCTL passes control information to the device driver
3.3 Library functions One problem with using the underlying system calls directly for input and output operations is that they are efficient:
1. Use system calls to affect system performance. System calls are expensive compared to function calls because Linux must switch from running user code to executing kernel code and then returning user code when executing system calls. One way to reduce this overhead is to minimize the number of system calls in the program and make every system call complete as much work as possible.
2. The hardware restricts the size of the data blocks that are read and written to the underlying system call once.
Using library functions, it is possible to write data blocks of arbitrary length efficiently, and the library function arranges to perform the underlying call when the data satisfies the block length requirement, which greatly reduces the overhead of the system call.
3.4 The underlying file access each running program is called a process, and it has some file descriptors associated with it. This is a number of small-value integers that you can access to open files or devices. When a program starts running, it typically has 3 file descriptors already open:
0: Standard input
1: Standard output
2: Standard error
The 3.4.1 write system calls the system call write to write the first nbytes bytes of the buffer buf to a file associated with the file descriptor Fildes. The following is the prototype of the write system call:
#include <unistd.h>
size_t write (int fildes, const void *buf, size_t nbytes);
Returns the number of bytes actually written (normal)
Returns 0 means no data is written
Returns 1 indicates an error occurred in the write call
Writing a program simple_write.c
The 3.4.2 read system calls the system call to read by reading Nbytes bytes of data from a file associated with the file descriptor Fildes and placing them in the data area buf.
#include <unistd.h>
size_t read (int fildes, void *buf, size_t nbytes);
Returns the number of bytes actually read in (normal)
Returning 0 means that no data has been read and the end of the file has been reached.
Returns 1 indicates that an error occurred in the read call.
Writing a program SIMPLE_READ.C
echo Hello there |./simple_read.exe
./simple_read.exe < Draft1.txt
When you run the program for the first time, use Echo to provide input to the program through the pipeline.
The second time the program is run, the input is redirected through the file.
3.4.3 Open System call in order to create a new file descriptor, you need to use the system call open.
#include <fcnt1.h>
#include <sys/types.h>
#include <sys/stat.h>
int open (const char *path, int oflags);
int open (const char *path, int oflags, mode_t mode);
To put it simply, open establishes a path to a file or device's access. If the call succeeds, it returns a file descriptor that can be used by read,write and other system calls. Prepares the name of the file or device to be opened as the parameter path passed to the function, the Oflags parameter specifies the action taken to open the file.
Open ("MyFile", O_creat, s_irusr| S_ixoth_);
Its role is to create a file named MyFile, file love you are the owner of the Read permission, other users have execute permissions.
The 3.4.4 close system call uses the close call to terminate the association between the file descriptor Fildes and its corresponding file. The file descriptor is freed and can be reused. The close call returns 0 when it succeeds, and returns 1 when an error occurs.
#include <unistd.h>
int close (int fildes);
The 3.4.5 IOCTL system calls the IOCTL call a bit like a hodgepodge, it provides an interface for controlling the behavior of the device and its descriptor and configuring the underlying services, terminals, file descriptors, sockets, and even tape drives that can have the IOCTL defined for them.
#include <unistd.h>
int ioctl (int fildes, int cmd,...);
Write a bottom-level program, COPY_SYSTEM.C, to copy a file to another file, one character at a to the next.
Then write an improved program, COPY_BLOCK.C, to improve efficiency by duplicating larger chunks of data.
3.4.6 rest with file-managed system calls 1.lseek system call
The Lseek system invokes a read-write pointer to the file descriptor Fildes.
2.fstat,stat and Lstat system calls
3.dup and DUP2 system calls
3.5 Standard I/O library standard I/O libraries and their header files Stdio.h provides a common interface for the underlying I/O systems. Using a standard I/O library is like using the underlying file descriptor, which requires opening a file to establish an access path. The return value of this operation will be used as a parameter to other I/O library functions. In the standard I/O library, the typeface corresponding to the underlying file description is the stream, which is implemented as a pointer to the structure file.
The 3.5.1 fopen function fopen function is similar to the underlying open system call, which is used primarily for file and terminal input and output. If you need explicit control over your device, it is best to use the underlying system call, as this avoids some potential problems with library functions, such as input and output buffering.
#include <stdio.h>
file* fopen (const char *filename, const char *mode);
Fopen opens the file specified by the filename parameter and associates it with a file stream. The mode parameter specifies how the file is opened, taking the values in the following string:
R Read-only, W write, and the length of the file truncated to zero; a write, new content appended at the end of the file, r+ update mode open (Read and write), w+ update mode, and the file length truncated to zero; A + is updated to open, new content is appended to the end of the file.
Fopen returns a non-null file* pointer on success, returns a null value on failure, and a null value defined in the header file stdio.h.
The 3.5.2 fread function Fread function is used to read data from a file stream. The data is read from the file stream stream into the data buffer pointed to by PTR. Both Fread and fwrite operate on data excitation, the size parameter specifies the length of each data record, and the counter Nitems gives the number of records to transfer. Its return value is the number of records successfully read to the data buffer.
#include <stdio.h>
size_t fread (void *ptr, size_t size, size_t nitems, file* stream);
The 3.5.3 fwrite function fwrite function extracts data records from the specified data buffer and writes them to the output stream.
#include <stdio.h>
size_t fwrite (const void *ptr, size_t size, size_t nitems, file* stream);
The 3.5.4 fclose function Fcloase function closes the specified file stream stream so that all data that has not been written out is written out.
#include <stdio.h>
int fclose (FILE *stream);
The function of the 3.5.5 fflush function fflush is to write out all the data in the file stream without writing it immediately.
#include <stdio.h>
int fflush (file* stream)
3.5.6 fseek function fseek function and the file stream function corresponding to Lseek system call. It specifies the location for the next read and write operation in the file stream. The offset and whence parameters are the same as the Lseek system call.
#include <stdio.h>
int fseek (file* stream, long int offset, int whence);
The 3.5.7 fgetc, getc, and GetChar function fgetc functions remove the next character from the file stream and return it as a character. When it reaches the end of the file or an error occurs, it returns EOF.
#include <stdio.h>
int fgetc (file* stream);
int getc (file* stream);
int GetChar ();
The GETC function acts as a fgetc, and the GetChar function acts as a getc (stdin), which reads a character from the standard input.
The 3.5.8 FPUTC, PUTC, and Putchar function FPUTC functions write a character into an output stream, which returns the value written and, if it fails, returns EOF
#include <stdio.h>
int FPUTC (int c, file* stream);
int PUTC (int c, file* stream);
int Putchar (int c);
The Putchar function is equivalent to PUTC (c, stdout), which writes a single character to the standard output.
3.5.9 fgets and gets function Fgets function reads a string from the stream stream of the input file.
#include <stdio.h>
Char *fgetc (char* s, int n, FILE *stream);
Char *gets (char* s);
Fgets writes the read character to the string in s direction until one of the following conditions occurs:
1. Line breaks encountered
2. n-1 characters have been transmitted
3. Reach the end of the file
It also passes the encountered newline character to the receiving string, plus a null byte to the end. A call transmits a maximum of n-1 characters because it must add an empty byte to the end string.
When completed successfully, Fgets returns a pointer to the string s.
If the end of the file has been reached, fgets sets the EOF ID of the file stream and returns a null pointer.
The Get function is similar to fgets, except that it reads data from the standard input and discards the line breaks encountered. It appends a null byte to the end of the receiving string.
Note: The get has no limit on the number of characters transmitted, so it may overflow its own transmit buffer. Therefore, you should avoid using get and replace it with fgets.

Linux Programming--File Operations (chapter III)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.