File Operations in Linux

Source: Internet
Author: User
Tags rewind

S_isreg () regular file
S_isdir () directory file
S_ischr () character Device File
S_blk () block Device File
S_fifo famous Pipeline File
S_islnk symbolic link file
S_sock socket File

# Include <sys/STAT. h>
# Include <fcntl. h>

Int open (const char * pathname, int Oflag,.../*, Modet mode */);
Correct return: file descriptor
Error returned:-1
Pathname is the name of the language to be opened or created.
* Open o_rdonly in read-only mode
* Open o_wronly in write-only mode
* Open o_rdwr in read/write mode
Note thatProgramWhen compatibility is large, the value of o_rdonly is 0, the value of o_wronly is 1, and the value of o_rdwr is 2.
In addition, it can include any combination of the following flag values using the bitwise logic plus symbol.
O_append starts from the end of the file each time a file is written.
O_creat: if the file does not exist, create the file. If this parameter is used, set the access method for the new file with the third parameter -- mode.
If the o_excl file exists but the o_create parameter is set, an error occurs. This parameter can be used to check whether the file exists and whether the file is created when the file does not exist.
O_trunc if the file exists and the file is correctly opened in write-only or read-write mode, the file length ends at 0,

S_irusr
S_iwusr The Write Permission bit of the file owner
S_ixusr file owner's execution permission limit
S_irgrp
S_iwgrp file user group write permission bit
S_ixgrp file user group execution permission limit
S_iroth
S_iwoth
S_ixoth File Execution permission limit for other users

The three useful bitwise combined orders are defined as follows:
S_irwxu is defined as (s_irusr | s_iwusr | s_ixusr)
S_irwxg is defined as (s_irgrp | s_iwgrp | s_ixgrp)
S_irwxo is defined as (s_iroth | s_iwoth | s_ixoth)

You can also use the following constant values to set the set_uid and set_gid bits.
S_isuid: set_uid
S_isgid: set_gid

When a process represents the creation of a document, its permission limit is changed by the umask value associated with the process. The process uses the following formula to determine the actual permission of the file to be created:
Mode &(~ Umask)
This indicates that the permission bit obtained on the file created by the program may be inconsistent with the mode parameter required in the open () call. If security issues are important, we can do something with the umask value.

 

Sometimes, before trying to open a specific file, you may want to check whether the process has accessed the file. In this case, an access system call can be completed. The access system calls the following methods:
# Include <unistd. h>
Int access (char * pathname, int mode );
Return correct: 1
Error message: 0
Among them, pathname is the file name mode to be verified is one of the following values of the package in unistd. h.
R_ OK check whether the calling process has read/write access
W_ OK checks whether the calling process has written access
X_ OK: Check whether the calling process has been accessed
F_ OK: Check whether the specified file exists

/**
* Create a new file 5.2.2.c
*/
# Include <sys/types. h>
# Include <sys/STAT. h>
# Include <fcntl. h>
Int creat (const char * pathname, mode_t Mode)
This function is equivalent:
Open (pathname, o_wronly | o_creat | o_trunc, Mode)

/**
* Random File Operations
*/
# Include <sys/stypes. h>
# Include <unistd. h>
Off_t lseek (int fd, off_t offset, int whence)
The FD parameter is a file descriptor, which indicates that the description of the opened file will be called for modification.
When specifying a new position for the file offset value, you only need to give a number as the new value. Generally, this value is equivalent to an offset value relative to the start position of the file. The other two possibilities are the offset value relative to the current file location or the offset value relative to the end of the file. These three possibilities are represented in Figure 5-2 in order to select their symbolic constants.
The offset parameter is a relative value. It is added to the selected base address and a new file offset value is given. The whence parameter can take one of the following three values (these values are defined in the <unistd. h> file )):
* Seek_set calculates the offset value from the beginning of the file.
* Seek_cur calculates the offset value from the offset of the current file.
* Seek_end calculates the offset value from the end of the file.

Bytes -------------------------------------------------------------------------------------------

Bytes --------------------------------------------------------------------------------------------

 

 

file operations (Stream)
only when a stream is associated with a file or device, you can perform various operations on the stream. This is called the stream opening operation. Only when the file exists, the nameuser has the permission to open the file, if the file is not locked by other users, the system allows the opening of a specific stream to successfully open the stream, if it succeeds, the system returns a pointer to the file structure, which can be used in subsequent operations. You can call the system function.
the following three system calls can open a standard input/output stream.
# include
file * fopen (const char * pathname, const char * type);
file * freopen (const char * pathname, const char * type, file * FP);
file * fdopen (INT filedes, const char * type );
the difference between the three system calls is that
fopen opens a specific file named by pathname.
freopen opens a specific file on a specific stream. First, close the opened stream specified by file * FP, and then open the stream specified by pathname. It is generally used to open a special file to replace the standard input stream and the standard output stream, standard Error output streams and other predefined streams.
fdopen maps a stream to an opened file. filedes is the descriptor of the file. This call can be successful only when the opened mode and the type-defined mode are the same. This opened file is generally a pipe file or network communication pipeline. These files cannot be opened through the fopen function of the standard input/output function. Only by calling a specific device can the file descriptor be obtained, then, use the fdopen function to associate a stream with the file.

Flow cleaning.
# Include <stdio. h>
Int fflush (File * FP)
Int fpurge (File * FP)
0 is returned correctly;
Returned error EOF;
File * FP is an opened stream, which has the following features:
Fflush stores the buffer content on the disk and clears the cache area.
Fpurge clears all data in the buffer, including unread or unwritten data. This is a type of damage cleaning, which is achieved by cutting off the power of the buffer zone.

Closing the stream.
# Include <stdio. h>
Int fclose (File * FP)
Return Value: 0
Error returned: EOF

Set streaming buffer attributes

the buffer attributes of a stream include the buffer size and type. The buffer types include the following, they have different characteristics
full Buffer: when this type of buffer is full, real input and output will be executed, this type stores the buffer data on a disk or outputs it to a terminal device. In most cases, this type of buffer is used.
row Buffer: in this case, when a line break is input in the buffer, the real input and output will occur. This buffer allows output by one character at a time on the terminal, the line buffer that represents the condition is usually used in the buffer zone connected to the terminal device.
no buffer: in this case, when a character is received, the real input and output are executed. Standard Error output is usually not buffered, this is why error messages are output as soon as they are generated and may be output on the screen in any situation.
# include
int setbuf (File * FP, char * BUF);
int setbuffer (File * FP, char * Buf, size_t size );
int setlinebuf (File * FP);
int setvbuf (File * FP, char * Buf, int mode, size_t size);
the returned result is correct: 0
error message returned: Non-0
the file * FP in these system calls is an opened stream, and the char * Buf is a user-defined buffer zone, size_t size is the buffer size, and INT mode is the stream type. It can take _ iofbf, _ iolbt, and _ ionbf, representing the full buffer, row buffer, and no buffer respectively. When calling these system functions, the stream must be opened so that the file * FP pointer exists. Of course, it is best not to perform other operations, because other operations are closely related to the nature of the buffer. Their respective features
setbuf: If the Buf is empty, the buffer type is set to no buffer. Otherwise, the buffer type is set to buffer. The full buffer size is the bufsiz constant, generally, it can be used as a function to activate the buffer. If the Buf is set to null, the buffer effect is disabled.
setbuffer: this function is consistent with setbuf, except that when the Buf is not empty, the size set to the full buffer is not the predefined value but the size.
setlinebuf: This function is used to set the buffer as a row buffer.
setvbuf: this function is the most basic function. The preceding three functions can be evolved from it.

stream locating (ftell, fseek)
# include
long ftell (File * FP)
correct return: the location of the message write pointer
error return: -1
int fseek (File * FP, long offset, int whence);
returned correctly: 0;
returned error: non-zero;
void rewind (File * FP)
no return value
the preceding three functions are described as follows:
ftell: For a binary file, the Data Writing pointer of a file starts from the beginning of the file and starts to count in bytes. This value can be obtained by calling this function.
fseek: This function is used to locate binary files, we must point out the offset of the Offset Value and the explanation using the biased method whence. The whence value can be in three cases
seek_set: Calculate the offset from the beginning of the file
seek_cur: offset from the current position of the file
seek_end: calculates the offset from the end of the file
rewind: This function is used to move the read/write pointer to the beginning of the file, we note that this function has no return value. By default, the system always calls this function successfully.
the previous introduction is for binary files, but it cannot be used for text files, in some non-Linux systems, the reading and writing pointer positions of text files are not simply measured in bytes, so ftell and fseek functions cannot be used, in Linux, The fseek function is used to locate text files. Whence must be seek_set. The offset value can only be 0 or the value obtained by ftell. This indicates that the access to a text file can only start or end.

Fgetpos and fsetpos
# Include <stido. h>
Int fgetpos (File * FP, fpos_t * POS );
Int fsetpos (File * FP, const fpos_t * POS );
Return Value: 0
Returned error: non-zero
These two functions are also stream locating operations. fgetpos can get the position of the read/write pointer while fsetpos can locate the position of the read/write pointer. They are different from the ftell and fseek described earlier:
Fgetpos and fsetpos use an abstract data structure, fpos_t. This is a record type for storing pointer locations. In a non-Linux system, fpos_t can also be defined as a record type for storing information about file write locations. Therefore, these two functions can also be used in non-Linux systems. As mentioned above, this function can be used for the convenience of text files.
The read/write pointer positions in ftell and fseek are recorded using long integers and can only be used in Linux.

Bytes -------------------------------------------------------------------------------------------

Bytes --------------------------------------------------------------------------------------------

Balanced input operation
The following three system calls are functions that allow us to read one character at a time.
# Include <stdio. h>
Int GETC (File * FP );
Int fgetc (File * FP );
Int getchar (void );
Returns the end Of the file or an error: EOF;
First, let's take a look at the differences and relationships between the three functions.
1. The function getchar serves to call the function GETC (stdin) and use the standard input stream as the data transmission capability.
2. The difference between GETC and fgetc is that GETC can be called as a macro, while fgetc can only be called as a function, so they have the following differences:
A. the GETC parameter cannot be an expression with side effects.
B. Because fgetc is a function, we can pass it as a parameter of other functions, but GETC cannot.
C. It takes longer to call the function fgetc than GETC. The get macro is designed to improve efficiency.
Next, let's take a look at the returned values of these three functions. They all convert the next character from the unsigned char type to the int type and return this integer, in this way, all possible values can be returned, including the EOF character. We know that in C, the EOF value is-1. Otherwise, the EOF value cannot be returned.

How to differentiate object end and object errors
In the previous introduction, we saw that the error in the file is the same as the return value of the end of the file, both of which are EOF. So how can we distinguish the two cases? The following system call can be implemented.
# Include <stdio. h>
Int ferror (File * FP)
Int feof (File * FP );
If the input is correct, return: non-zero
If the input is incorrect, zero is returned.

In most cases, these two flags are saved in the file structure. One is the error flags and the other is the ending flags. The above two functions are judged based on these two flags, the two flags can be cleared by the following functions.
Void clearerr (File * FP );

Actions to push characters back to the buffer zone
# Include <stdio. h>
Int ungetc (int c, file * FP)
Return Value: integer c
Error message: EOF
The push-back character will be returned in the next message operation. In principle, it can support any number of push-back character operations. However, it is enough to be used only once, in addition, pushing back multiple characters is not supported by Puqi, so we do not advocate pushing back multiple characters.
The characters we push back do not necessarily need to be read from the previous one. The EOF character cannot be pushed back. But when we reach the end of a letter, we can push back a character, in the next read operation, we will get this character, and the subsequent message operation will get the EOF character,
The operation of pushing back characters is used in the Compilation Program. During the compilation process, we sometimes need to read more than one character to determine how to process the current character, with this function, we can push back the character that we want to read for future calls.

Balanced output operations
# Include <stdio. h>
Int putc (int c, file * FP );
Int fputc (int c, file * FP );
Int putchar (int c, file * FP );
Like the relationship between the three input functions, putchar (c) is equivalent to putc (C, stdout), putc is encoded as a macro, and fputc is just a common function.

one-row input operation
# include
char * fgets (char * Buf, int N, Fiel * FP);
char * gets (char * BUF);
correct return: buf;
error message returned: NULL pointer
both functions need to specify the buffer address for receiving input, that is, Buf has the following features:
. fgets needs to specify the number of characters received n and the stream structure pointer FP. Generally, it reads a row and saves the content of the row, including the end mark of the row, to the Buf together, end with a NULL Character 0. In this case, the content of this line must include the end of the line and cannot exceed n-1 characters. If the number of characters exceeds n-1, only one part of the row is read and the end is null. The next time fgets is called, the next part of the row is read.
B. Gets is input from the standard input device. It is a controversial function. The problem is that the caller is allowed to specify the buffer size. If the size of a row is larger than the buffer size, the buffer overflow is allowed, and the contents under the buffer in the memory will be destroyed. This method has been used to create viruses, so although Standard C provides this function, it is best not to use it.

One-row output operation
# Include <stdio. h>
Int fputs (const char * STR, Fiel * FP );
Int puts (const char * Str );
Correct return: non-negative
Error returned: EOF
Char * STR is the string to be output. Their respective features are as follows:
A. the fputs function is used to output a string ending with 0 to a specific stream. The character 0 at the end is not output. Because the string does not need to end with a linefeed, therefore, this function does not necessarily output a row at a time. In most cases, it outputs a row at a time, but it is not necessary.
B. the puts function is used to output the string ending with 0 to the standard output device. It also does not output the end character 0, but this function must output a line break, therefore, the puts function must output a row at a time. This function is not as insecure as its corresponding function gets. Because using this function does not have to deal with line breaks, it is simpler than fputs.

Direct input/output operations
# Include <stdio. h>
Size_t fread (void * PTR, size_t size, size_t nobj, file * FP );
Size_t fwrite (const void * PTR, size_t size, size_t nobj, file * FP );
Return Value: the actual number of reads or writes.
PTR is a pointer to several structures. This structure is the smallest processing unit of input and output. size is the size of the structure, which is generally obtained using the sizeof () function; nobj is the number of structures to be processed. FP is the stream pointer.

SELF: http://hi.baidu.com/phps/blog/item/5bf79613e410e4806438db31.html

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.