Linux File Input and Output

Source: Internet
Author: User
Tags flock flock lock rewind
1. File Operations (buffering) based on file pointers)In Linux, most resources can be processed as files. Common file types include: l common files l unknown pipelines and named pipelines l directory l device l symbols connect l socket common files: Also known as disk files, in addition, it can store random data (with the ability to freely locate seek to a certain position). Pipeline: a data channel that sends data from one end and receives data from the other end. directory: it is also called a directory file, which contains a simple file that is stored in the file list in the directory. Device: a special file that provides interfaces for most physical devices. It can be divided into two types: memory devices and Block devices. Only one byte of data can be read and written by devices at a time, including the modem, middle end, printer, sound card, and mouse. Block devices must read or write data in blocks of a certain size, block devices include CD-Rom, Ram drives, and disk drives. Generally, character devices are used to transmit data and Block devices are used to store data. Symbolic Link: similar to the shortcut in windows and the alias in Linux, it refers to the file that contains the path to another file. Socket: in Linux, sockets can also be processed as files. File operation functions based on file pointers are part of the ANSI standard function library. 1.1. Create, open, and close a filePrototype: # include <stdio. h> file * fopen (const char * Pach, const char * mode); file * fdopen (int fd, const char * mode); int fclose (File * stream ); fopen opens or creates a file in mode. If the file is successfully opened, a file pointer is returned. If the file fails, null is returned. the access permission for the files created by fopen is determined by combining 0666 with the current umask. List of modes available
Mode Read Write Location Truncate original content Create
RB Y N File Header N N
R + B Y Y File Header N N
WB N Y File Header Y Y
W + B Y Y File Header Y Y
AB N Y End of File N Y
A + B Y Y End of File N Y
In Linux, 'B' (Binary) in the mode can be removed, but we recommend that you do not remove it to maintain compatibility with other systems. AB and A + B are append modes. In both modes, no matter where the file read/write points are located, data is added at the end of the file when writing data, therefore, it is suitable to ensure data integrity when multiple processes write the same file. Fdopen opens a file pointer Based on the opened file descriptor. Opening a file descriptor and a file pointer to the same file may cause problems. However, in a multi-process program, file descriptors are often required, so such mixed file operations must be mastered. 1.2. Read and Write filesThere are many data read/write functions based on file pointers, which can be divided into the following groups: Data Block read/write: # Include <stdio. h> size_t fread (void * PTR, size_t size, size_t nmemb, file * stream); size_t fwrite (void * PTR, size_t size, size_t nmemb, file * stream ); fread reads nmemb elements from the file stream and writes them to the memory directed by PTR. The size of each element is size byte. fwrite reads nmemb elements from the memory directed by PTR, size of each element written to a file. All file read/write functions start to read and write from the current read/write point of the file. After reading, the current read/write point automatically moves the size * nmemb byte. Formatted read/write:# Include <stdio. h>  Int printf (const char * format ,...); int fprintf (File * stream, const char * format ,...); int sprintf (char * STR, const char * format ,...); int snprintf (char * STR, size_t size, const char * format ,...); # include <stdarg. h> int vprintf (const char * format, va_list AP); int vfprintf (File * stream, const char * format, va_list AP); int vsprintf (char * STR, const char * format, va_list AP); int vsnprintf (char * STR, size_t size, const char * format, va_list AP); printf is equivalent to fprintf (stdout, format ,...); the formatted string starting with F and VF is written into the file stream, and the formatted string starting with S and VS is written into the STR string. functions starting with V are often called within a variable number of parameters, for example, int myprintf (const char * format ,...) {va_list lstarg; file * pstream=fopen(“a.txt "," AB "); va_start (lstarg, pszformat); vfprintf (pstream, pszformat, lstarg); va_end (lstarg ); fclose (pstream );} Character read/write:Use the following function to read and write one character at a time # include <stdio. h> int fgetc (File * stream); int fputc (int c, file * stream); int GETC (File * stream); int putc (int c, file * stream ); int getchar (void); int putchar (int c); getchar and putchar read and write data from the standard input/output stream, and other functions read and write data from the file stream. Note that this Group reads and writes only one byte of data each time, but the type is expressed as an integer. Row read/write:Char * fgets (char * s, int size, file * stream); int fputs (const char * s, file * stream); int puts (const char * s ); char * gets (char * s); fgets and fputs read and write a row of data from the file stream; puts and gets read and write a row of data from the standard input/output stream. Fgets can specify the size of the target buffer. Therefore, it is secure relative to gets. However, when fgets is called, if the number of characters in the current row in the file is greater than the size, the next fgets call will take effect, the remaining characters of the row will be read. When fgets reads a line of characters, the line break at the end of the line will be retained. Fputs does not automatically add line breaks at the end of a row, but puts automatically adds a line break to the standard output stream. File Location:File Location refers to reading or setting the current read/write point of the file. All functions that read and write data through the file pointer read and write data from the current read/write point of the file. Common functions include: # include <stdio. h> int fseek (File * stream, long offset, int whence); long ftell (File * stream); void rewind (File * stream); fseek sets the current read/write point to the offset, whence can be seek_set, seek_cur, and seek_end. These values determine the offset calculated from the file header, current point, and end. ftell obtains the current read/write point. Rewind moves the current read/write point of the file to the file header 0. 1.3. Directory operations Get and change the current directory:The prototype is: # include <unistd. h> char * getcwd (char * Buf, size_t size); // get the current directory int chdir (const char * path); // modify the current directory int fchdir (int fd ); // modify the current directory using the file descriptor Create and delete directories:Prototype: # include <sys/STAT. h> # include <sys/types. h> # include <unistd. h> int mkdir (const char * pathname, mode_t mode); // create a directory. The mode permission is int rmdir (const char * pathname). // Delete the Directory Get directory information:The prototype is: # include <sys/types. h> # include <dirent. h> dir * opendir (const char * Name); // open a directory, struct dirent * readdir (dir * DIR); // read information about a directory, return the struct pointer void rewinddir (dir * DIR) of this item. // locate the int closedir (dir * DIR) header of the directory file ); // The steps for disabling directory files to read directory information are as follows: 1. Use the opendir function to open the Directory; 2. Use the readdir function to read the content of the Directory iteratively. If the directory has been read to the end, to start reading again, you can use the rewinddiw function to locate the file pointer to the starting position of the directory file. 3. Use the closedir function to close the directory. Example: # include <stdio. h> # include <sys/types. h> # includ E <dirent. h> int main (INT argc, char * argv []) {dirent * pdirinfo; dir * pdir; // If (argc <2) pdir = opendir (". "); else pdir = opendir (argv [1]); If (pdir = NULL) {perror (" Open dir fail! "); Return-1;} while (pdirinfo = readdir (pdir) printf (" % s/n ", pdirinfo-> d_name); closedir (pdir ); return 0 ;} 1.4. Standard input/output streamWhen the process starts running, three files of the corresponding device are automatically opened. They are standard input, output, and error streams, which are represented by the Global File pointers stdin, stdout, and stderr respectively, stdin has a readable attribute. By default, it refers to reading input from the keyboard. stdout and stderr have writable attributes. By default, it points to the screen input data. Example: # include <stdio. h> # include <unistd. h> int main () {char szbuf [32]; printf ("input string:"); // output a string fgets (szbuf, sizeof (szbuf) to the screen ), stdin); // read a line of string fprintf (stdout, "the string is: % s", szbuf) from the keyboard; // output a line of string return 0 to the screen ;} 2. File Operations Based on file descriptors (non-buffered) 2.1. file descriptorThe kernel maintains an open file record table for each process. The file descriptor is a small positive integer that represents a record table, by using file descriptors and a set of file operation functions based on file descriptors, you can perform operations such as reading, writing, creating, and deleting files. Common file descriptor-based functions include open, creat, close, read, write, ftruncate, lseek, fsync, fstat, fchown, flock, fcntl, dup, dup2, select, and IOCTL. File Operations Based on file descriptors are not ansi c functions. 2.2. Open, create, and close a fileBoth open and creat can open and create functions. The prototype is # include <sys/types. h> # include <sys/STAT. h> # include <fcntl. h> int open (const char * pathname, int flags); int open (const char * pathname, int flags, mode_t mode); int creat (const char * pathname, mode_t mode); flags and mode are the compositing values of a group of masks. Flags indicates the mode of opening or creating the mask, and mode indicates the file access permission. Optional flags
Mask Description
O_rdonly Open in read-only mode
O_wronly Open in write-only mode
O_rdwr Open in read/write mode
O_creat If the file does not exist, create the file
O_excl It is used only with o_creat. If the file already exists, force open to fail.
O_trunc If the file exists, set the file length to 0.
O_append When you call write, the file pointer is automatically moved to the end of the file to write the same file in multiple processes.
O_nonblock Open in non-blocking mode
O_nodelay Open in non-blocking mode
O_sync Returned only when data is actually written to a physical device
Int creat (const char * pathname, mode_t mode); equivalent to open (pathname, o_creat | o_trunc | o_wronly, mode); after the file is used up, you should call close to close it, once close is called, all the locks added by the process to the file are released, and the reference count of the file is reduced by 1. Only after the reference count of the file is changed to 0, the file is actually closed. The file reference count is mainly used for transferring file descriptors between multiple processes. 2.3. Read and Write filesThe function prototype for reading and writing files is: # include <unistd. h> ssize_t read (int fd, void * Buf, size_t count); ssize_t write (int fd, const void * Buf, size_t count ); 2.4. File LocationThe lseek function sets the file pointer to the position where the offset value is offset relative to whence # include <sys/types. h> # include <unistd. h> off_t lseek (INT Fildes, off_t offset, int whence ); whence can be a seek_set of the following three constants. From the file header, seek_cur is calculated. From the current pointer, seek_end is calculated from the end of the file. 2.5. Get File InformationYou can use the fstat and stat functions to obtain the file information. After the call, the file information is filled in the struct stat Buf struct. The prototype is: # include <sys/types. h> # include <sys/STAT. h> # include <unistd. h> int Stat (const char * file_name, struct stat * BUF); int fstat (INT filedes, struct stat * BUF); struct stat is defined as: struct stat {dev_t st_dev; /* if it is a device, return the device identifier; otherwise, it is 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;/* owner ID */gid_t st_gid;/* Group ID */dev_t st_rdev;/* device type */off_t st_size; /* file size, in bytes */blksize_t st_blksize;/* block size */blkcnt_t st_blocks;/* number of blocks */time_t st_atime;/* actual access */time_t st_mtime; /* finally modify the actual */time_t st_ctime;/* creation time */}; For the struct member st_mod, there is a set of macros that can be used to determine the file type.
Macro Description
S_islnk (Mode) Determine if it is a symbolic link
S_isreg (Mode) Determine whether it is a common file
S_isdir (Mode) Determine if it is a directory
S_ischr (Mode) Determine whether the device is a confirmed Device
S_isblk (Mode) Determine whether it is a block Device
S_isfifo (Mode) Determine whether a named pipe is used
S_issock (Mode) Determine whether it is a socket
  2.6. File LockingWhen multiple processes perform read/write access to the same file, the file is sometimes locked to ensure data integrity. You can use fcntl to lock and unlock files. # Include <unistd. h> # include <fcntl. h> int fcntl (int fd, int cmd, struct flock * Lock); Set cmd to f_getlk or f_setlk to get or set file lock information. The struct flock parameter indicates the file lock information. There are two types of File locks: Read locks (shared locks) and write locks (mutex locks ). For files with read locks added, adding the write lock will fail, but other processes are allowed to continue to apply the read lock. For files with the write lock, both read locks and write locks will fail. Note: The filelock is only valid for other processes that attempt to lock the file. It is invalid for processes that directly access the file. Example: # include <string. h> # include <stdlib. h> # include <stdio. h> # include <fcntl. h> # include <errno. h> # include <unistd. h> # include <sys/types. h> # include <sys/STAT. h> bool lockfile (int fd, int itype) {struct flock lock; lock. rochelle whence = seek_set; // lock from the file header. rochelle pid = getpid (); // current process ID lock. rochelle start = 0; // start lock point, lock. rochelle Len = 0; // The end lock point. 0 indicates that the entire file is locked. l_type = itype; // lock type if (fcntl (FD, f_setlk, & lock) = 0) return t Rue; perror ("lock fail"); Return false;} int main (INT argc, char * argv []) {int FD = open (". /a.txt ", o_creat | o_rdwr); int ilock = 0; If (FD <0) {printf (" errno: % d/N ", errno ); perror ("Open fail"); Return-1;} fchmod (FD, 0666); If (argc> 1) {If (strstr (argv [1], "Write") {If (! Lockfile (FD, f_wrlck) {return-3 ;}} else if (strstr (argv [1], "read") {If (! Lockfile (FD, f_rdlck) {return-3 ;}} lseek (FD, 0, seek_end); If (write (FD, "ABC", 3) <0) {perror ("Write fail"); Return-2;} Sleep (10); close (FD); Return 0 ;} 2.7. file descriptor ReplicationThe DUP and dup2 functions can replicate file descriptors. The prototype is: # include <unistd. h> int DUP (INT oldfd); int dup2 (INT oldfd, int newfd); copying a file descriptor refers to directing another file descriptor to the same open file, it is completely different from assigning values directly to file descriptor variables. For example, directly assigning values to descriptor variables: Char szbuf [32]; int FD = open (". /a.txt ", o_rdonly); int fd2 = FD; close (FD); // cause the file to immediately close printf (" read: % d/N ", read (fd2 ), szbuf, sizeof (szbuf)-1); // read failed close (fd2); // meaningless in this case, the values of the two file descriptor variables are the same, point to the same open file, but the file opening reference count of the kernel is still 1, so close (FD) or close (fd2) will cause the file to be closed immediately. Replication of descriptors: Char szbuf [32]; int FD = open (". /a.txt ", o_rdonly); int fd2 = DUP (FD); close (FD); // the file will not be closed yet, in this case, you can access the printf ("Read: % d/N", read (fd2), szbuf, sizeof (szbuf)-1), close (fd2) through fd2 ); // when the reference count of the kernel is changed to 0, the file officially closes dup2 (INT fdold, int fdnew), which is also used for descriptor replication, the new descriptor is specified by the user using the fdnew parameter, instead of being selected by the kernel like DUP. For dup2, if fdnew has pointed to an opened file, the kernel will first close the original file pointed to by fdnew. If the return value of successful dup2 is the same as that of fdnew, otherwise-1 is used to consider the result of the following program: # include <stdlib. h> # include <stdio. h> # include <unistd. h> # include <sys/types. h> # include <sys/STAT. h> int main (INT argc, char * argv []) {char szbuf [32] = {0}; int FDA = open (". /a.txt ", o_rdonly); int FDB = open (". /B .txt ", o_rdonly); int fdbb = DUP (FDB); int fda2 = dup2 (FDA, FDB); printf (" FDA: % d FDB: % d fdbb: % d fda2: % d ", FDA, FDB, fdbb, fda2); read (FDB, szbuf, sizeof (szbuf)-1); printf (" result: % s/n ", szbuf); close (FDA); close (FDB); close (fdbb); close (fda2 );} 2.8. Standard input/output file descriptorIt corresponds to a standard input/output stream. The underlying implementation is represented by standard input, standard output, and standard error file descriptor. They are represented by three macros: stdin_fileno, stdout_fileno, and stderr_fileno. The values are 0, 1, and 2. Example: # include <stdio. h> # include <unistd. h> # include <string. h> int main () {char szbuf [32], szbuf2 [50]; printf ("input string:"); fflush (stdout); // to refresh the standard output stream, "input string" int iret = read (stdin_fileno, szbuf, sizeof (szbuf); szbuf [iret] = 0; // read is the data read without a type pointer. It does not automatically add a 0-End mark after the buffer. Sprintf (szbuf2, "the string is: % s", szbuf); write (stdout_fileno, szbuf2, strlen (szbuf2); Return 0;

}

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.