Linux C Note file (i)

Source: Internet
Author: User
Tags function prototype

I. File types included under Linux 1. Common Files 2. directory file 3. Character special Files 4. Block Special file 5.FIFO 6. Socket 7. Symbolic connection

Two. Access file control for Linux
chmod using syntax
$ chmod [options] mode[,mode] file1 [file2 ...]
To view the properties of a file or directory using the LS command
$ ls-l File
The chmod command can use octal numbers to specify permissions. The permission bits of a file or directory are controlled by 9 permission bits, each of which is a set of three bits, which are read, written, executed by the owner (user), read, written, executed by the Users (group), and read, written, and executed by other users. Historically, file permissions were placed in a bitmask, with the bits specified in the mask set to 1, to indicate that a class had a corresponding priority.
A numerical description of the octal syntax of chmod;
R 4 W 2 x 1-0
The owner's authority is expressed in numbers: the sum of the numbers of the three permission bits of the master. such as rwx, that is, 4+2+1, should be 7.
The permissions of the user group are expressed in numbers: the sum of the number of permission bits that belong to the group. such as rw-, that is, 4+2+0, should be 6.
Other user's permission number expression: The sum of the numbers added to the other user's permission bits. such as R-x, that is, 4+0+1, should be 5.
My_chomd.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>

int main (int argc,char **argv)
{
int mode; Permissions
int Mode_u; Owner Permissions
int mode_g; Owner Permissions
int mode_o; Other user rights
Char *path;

if (ARGC < 3) {
printf ("%s <mode num> <target file \n>", argv[0]);
Exit (0);
}

mode = Atoi (argv[1]);
if (Mode > 777 | | Mode < 0) {
printf ("mode num error!\n");
Exit (0);
}
Mode_u = mode/100;
Mode_g = (mode% 100)/10;
Mode_o = mode% 10; or mode_o= mode-(Mode_u *)-(MODE_G * 10);
mode = (Mode_u * 8 * 8) + (MODE_G * 8) + mode_o; Eight-Step conversion
Path = argv[2];

if (chmod (path,mode) = =-1) {
Perror ("chmod error");
Exit (1);
}

return 0;
}

In the program, the permission change successfully returns 0, the failure returns 1, and the error code is stored in the system pre-defined variable errno.
In the above program, atoi This function call is to convert the string to integer, for example: Atoi ("777") The return value is the integer type of 777. For chmod functions, the second parameter is generally taken or calculated between the macros listed above.

Three. Opening and closing of file creation
1.open function
Call O p e n function/to open or create a file.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open (const char * pathname, int oflag, .../*, mode_t mode */)
Returns: If successful as a file descriptor, if error is-1
We will write the third parameter as ..., which is the method that ANSI C describes the number and type of remaining arguments that can vary. For the O p e n function, the third parameter is used only when a new file is created. In this function prototype, this parameter is placed in the comment.
Pathname is the name of the file to open or create. The Oflag parameter can be used to illustrate multiple selections for this function. Use one or more of the following constants to make or operate the Oflag parameter (these constants are defined in the < Fcntl. h > Header file):
O_rdonly read-only open.
o_wronly only write open.
O_rdwr Read, write open.

You should specify only one of these three constants. The following constants are selectable:
O_append is added to the end of the file each time it is written.
o_creat Create this file if it does not exist. When using this selection, it is necessary to describe the third parameter mode, which describes the access permission of the new file to the throne.
O_excl If an O _ C R E at is specified and the file already exists, an error occurs. This tests whether a file exists and if it does not, it becomes an atomic operation to create the file.
O_trunc If this file exists and is open for read-only or write-only success, the length is truncated to 0.
O_noctty This device is not assigned as the control terminal for this process if pathname refers to the terminal equipment.
O_nonblock If pathname refers to an F I F O, a block special file, or a character special file, this option sets the non-blocking mode for this open operation and subsequent I/O operations for this file.




2.creat function
You can also use the creat function to create a new file.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int creat (const char * pathname, mode_t mode)
Returns: If the file descriptor is open only for write-only, if the error is-1
Note that this function is equivalent to:
Open (Pathname, o_wronl | O_creat | O_trunc, mode);
One disadvantage of creat is that it opens the created file in a write-only manner. Before providing a new version of open, if you want to create a temporary file and write the file first, and then read the file again, you must first call creat, close, and then call Open. You can now call open in the following ways:
Open (Pathname, O _ R D W r| O _ C R E A t| O_trunc, mode);

3.close function
You can close an open file by using the Close function:
#include <unistd.h>
int close (int filedes);
Return: If the success is 0, if the error is-1
Closing a file also frees all record locks that the process adds to the file.
When a process terminates, all its open files are automatically closed by the kernel. Many programs use this feature without explicitly closing open files with close

Four. file reading and writing
1.read function
Read the data from the open file with the Read function.
#include <unistd.h>
ssize_t Read (int fd, void *buf, Size_count);
Returns: the number of bytes read, if the end of the file is 0, if the error is-1
If read succeeds, the number of bytes read is returned. Returns 0 if the end of the file has been reached.
There are a number of situations in which the number of bytes actually read is less than the number of bytes required to read:
• When reading a normal file, the end of the file is reached before the required number of bytes are read. For example, if you have 3 0 bytes before reaching the end of the file and require reading 1 0 0 bytes, read returns 3 0, and the next time you call read, it returns 0 (the end of the file).
• When reading from an end device, it is usually read one line at a time
• When reading from the network, the buffer mechanism in the network may cause the return value to be less than the number of bytes required to read.
• Some record-oriented devices, such as tapes, return up to one record at a time. The read operation starts at the current offset of the file and increases the number of bytes actually read before returning successfully.
Its return value must be a signed integer (ssize_t) to return the number of positive bytes, 0 (for end of file), or 1 (error). Finally, the third parameter is historically a unsigned integer to allow a 1 6-bit implementation to read or write to 6 5 5 3 4 bytes at a time.

2.write function
Write the data to the open file with the Write function.
#include <unistd.h>
ssize_t Write (int fd, const void *buf, size_t count)
Returns: If the number of bytes written is successful, if the error is-1
The return value is usually different from the value of the parameter n B y t e s, otherwise it indicates an error. A common cause of errors in W R i-e is that the disk is full or exceeds the file length limit for a given process
For normal files, the write operation starts at the current offset of the file. If an O _ A p p E N D selection is specified when the file is opened, the file offset is set at the current end of the file before each write operation. After a successful write, the file offset increases the number of bytes actually written.

Five. Movement of read and write pointers to files
Lseek function
Each open file has a "current file offset" associated with it. It is a nonnegative integer that measures the number of bytes computed at the beginning of the file.
Typically, read and write operations start at the current file offset and increase the amount of displacement by the number of bytes read or written. By default, when a file is opened, the offset is set to 0 unless you specify O _ a p p E N D to select the item.
You can call Lseek to explicitly locate an open file.
#include <sys/types.h>
#include <unistd.h>
off_t lseek (int fildes, off_t offset, int whence);
Return: If the new file is successfully displaced, if the error is-1
The interpretation of the parameter offset is related to the value of the parameter W h e n c e.
• If whence is seek_set, set the offset of the file to offset bytes from the beginning of the file.
• If whence is seek_cur, set the offset of the file to its current value and offset to positive or negative.
• If whence is seek_end, set the file's offset to the file length plus offset, which can be positive or negative.
If Lseek executes successfully, the new file offset is returned, which can be used to determine the current
Displacement Amount:
off_t
Currpos;
Currpos = Lseek (FD, 0, seek_cur);
This method can also be used to determine whether the amount of displacement is set by the file involved. If the file descriptor refers to a pipe or F I f O, then Lseek returns-1, and errno is set to Epipe.

Linux C Note file (i)

Related Article

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.