File manipulation based on file descriptors (non-buffered)

Source: Internet
Author: User
Tags integer numbers

1.1. File Descriptor: The kernel maintains a record table of open files for each process, the file descriptor is a small positive integer (0-1023), it represents an item of the record table, through the file descriptor and a set of file manipulation functions based on the file descriptor, you can implement the file read, write, create, delete and other operations. Commonly used file descriptor-based functions are open (open), creat (Create), close (off), read (read), write (write), ftruncate (change file size), Lseek (locate), Fsync (synchronous), Fstat (get file status), Fchmod (permissions), Flock (locking), Fcntl (Control file properties), DUP (copy), dup2, select, and IOCTL. (The specific function if you don't know how to use it you can use the man function name to see Help) 1.2. Open, create, and close files

Both open and creat are capable of opening and creating functions that are prototyped as

#include <sys/types.h>//header files

#include <sys/stat.h>

#include <fcntl.h>

int open (const char *pathname, int flags); How file names are opened

int open (const char *pathname, int flags, mode_t mode);//file name Open with permission

int creat (const char *pathname, mode_t mode); FileName permissions//It's not used anymore.

The creat function is equivalent to Èopen (pathname,o_creat| o_trunc| O_wronly,mode);

The open () function returns 1 when there is an error, and the relevant parameters are as follows:

Both the flags and mode are a set of masked composite values, flags indicates the way to open or create, and mode represents the access rights of the file.

The optional options for flags are

Mask

Meaning

O_rdonly

Open in read-only mode

O_wronly

Open in a write-only manner

O_rdwr

Open in a read-write manner

O_creat

If the file does not exist, create the file

O_excl

Only with O_creat, forcing open to fail if the file already exists

O_trunc

If the file exists, the length of the file is as long as 0

O_append

An appended way to open a file, each time the write is called, the file pointer is automatically first moved to the end of the file, for multiple processes to write the same file.

O_nonblock

Open non-blocking mode, no matter if there is no data read or wait, will return to the process immediately.

O_nodelay

Open non-blocking mode

O_sync

Open files synchronously and return only if the data is actually written to the physical device device

Note: The file descriptor-based open function in Linux, for a nonexistent file, cannot be opened by O_wronly, and the o_creat option must be added.

1.3. Read and Write files

The function prototypes for reading and writing files are:

#include <unistd.h>

ssize_t Read (int fd, void *buf, size_t count);//File description Word buffer length

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

For the read and write functions, an error returns 1, after reading, 0 is returned, and the number of reads and writes is returned in other cases.

Example: Copies the contents of Aaa.txt to Bbb.txt, where Bbb.txt does not exist at first.

#include <stdio.h>

#include <stdlib.h>/Include exit

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <errno.h>//Output error with Perror

#include <unistd.h>

#define FILENAME1 "./aaa.txt"//Use macro to define the path of the file, you can change the

#define FILENAME2 "./bbb.txt"

Main ()

{

Char buf[512] = {0};

int fo1 = open (FILENAME1, o_rdonly);//fo1,fo2 are file descriptors.

int Fo2 = creat (FILENAME2, 0755); Create a file

int Fo2 = open (FILENAME2, o_wronly | O_creat);

if (( -1 = = Fo1) | | ( -1 = = Fo2))

{

Perror ("Open failed!\n");

Used to output error messages. Similar to: fputs ("Open failed\n", stderr);

Exit (-1);

}

int FR = 0;

while (FR = Read (fo1, buf, sizeof (BUF))) > 0)

If read reads successfully, returns the length, otherwise, returns-1

{

int fw = Write (Fo2, buf, FR);

if (-1 = = FW)

{

Perror ("Write failed!");

Exit (-1);

}

}

Close (FO1);

Close (Fo2);

}

1.4. Document positioning

function Lseek Sets the position of the file pointer to offset relative to whence

#include <sys/types.h>

#include <unistd.h>

off_t lseek (int fd, off_t offset, int whence);//fd file Description Word

Whence can be one of the following three constants

Seek_set starting from the file header

Seek_cur The current pointer starts the calculation

Seek_end starting at the end of the file

This function can be used to implement the file hole (for a new empty file, you can locate the offset file at the beginning of the 1024 bytes, write a character, it is equivalent to the file allocated 1025 bytes of space, forming a file hole) is usually for multi-process communication between the time of shared memory.

int main ()

{

int fd = open ("C.txt", O_wronly | O_creat);

Lseek (FD, 1024x768, seek_set);

Write (FD, "a", 1);

Close (FD);

return 0;

1.5. Get file information

The file information can be obtained through the FSTAT and stat functions, and when the call is complete, the file information is filled into the struct struct stat variable, and the function prototype is:

#include <sys/types.h>

#include <sys/stat.h>

#include <unistd.h>

int stat (const char *file_name, struct stat *buf); File name stat struct pointer

int fstat (int fd, struct stat *buf); File description Word stat struct pointer

The structure stat is defined as:

struct STAT {

dev_t St_dev; /* If it is a device, return the device specifier, otherwise 0*/

ino_t St_ino; /* I node number */

mode_t St_mode; /* File type */

nlink_t St_nlink; /* Number of links */

uid_t St_uid; /* is the main ID */

gid_t St_gid; /* Group ID */

dev_t St_rdev; /* Device Type */

off_t st_size; /* File size, byte representation */

blksize_t st_blksize; /* Block Size */

blkcnt_t st_blocks; /* Number of blocks */

time_t St_atime; /* Last access Time */

time_t St_mtime; /* Last Modification time */

time_t St_ctime; /* Create Time */

};

For member St_mode of a struct, there is a set of macros that can be judged by file type

Macro

Describe

S_islnk (Mode)

Determine if it is a symbolic link

S_isreg (Mode)

Determine if it is an ordinary file

S_isdir (Mode)

Determine if it is a directory

S_ISCHR (Mode)

Determine if the device is a character type

S_ISBLK (Mode)

Determine if a block device

S_isfifo (Mode)

Determine if it is a named pipe

S_issock (Mode)

Determine if it is a socket

Usually used to determine if (S_isdir (St.st_mode)) {}

1.6. Copying of file descriptors

The system invoke function DUP and dup2 can implement the file descriptor replication, often used to redirect the process of stdin (0), stdout (1), stderr (2).

The DUP returns a new file descriptor (the minimum number of file descriptors that are not used). This new descriptor is a copy of the old file descriptor. This means that the two descriptors share the same data structure.

DUP2 allows the caller to use a valid descriptor (OLDFD) and a target descriptor (NEWFD), when the function returns successfully, the target descriptor becomes a copy of the old descriptor, at which point the two file descriptors now point to the same file, and are the files to which the function's first argument (that is, OLDFD) points.

The prototypes are:

#include <unistd.h>//header file contains

int dup (int oldfd);

int dup2 (int oldfd, int newfd);

Copying a file descriptor means pointing to the same open file with another file descriptor, which is completely different from assigning a value directly to a file descriptor variable, for example:

Direct assignment of Descriptor variables:

Char szbuf[32];

int Fd=open ("./a.txt", o_rdonly);

int fd2=fd; Similar to the C language pointer assignment, when the release of a time, the other has been unable to operate

Close (FD); Cause the file to close immediately

printf ("read:%d\n", read (FD2), szbuf,sizeof (SZBUF)-1); Read failed

Close (FD2); No meaning

In this case, the values of the two file descriptor variables are the same, pointing to the same open file, but the kernel file opens the reference count or 1, so close (FD) or close (FD2) causes the file to be closed immediately.

1.7. Standard input/output file descriptor

corresponding to the standard input and output stream, the implementation at the lower level is represented by standard input, standard output, and standard error file descriptors. They are represented by three macros, Stdin_fileno, Stdout_fileno, and Stderr_fileno, respectively, with values of 0, 1, and 23 integer numbers.

Standard input File Descriptor èstdin_filenoè0

Standard output File descriptor èstdout_filenoè1

Standard error Output file descriptor èstderr_filenoè2

File manipulation based on file descriptors (non-buffered)

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.