Linux system programming file and I/O (I): file opening and closing

Source: Internet
Author: User

I. file descriptor

For Linux, all operations on devices or files are performed through file descriptors. When a file is opened or created, the kernel returns a file descriptor (non-negative integer) to the process ). Subsequent operations on the file only need to use the file descriptor to record information about the opened file (file structure) in the kernel ).
When a process starts, three files are opened by default, including standard input, standard output, and standard error. The corresponding file descriptors are 0 (stdin_fileno), 1 (stdout_fileno), and 2 (stderr_fileno ), these constants are defined in unistd. h header file.


Fileno: converts a file pointer to a file descriptor.
Fdopen: convert a file descriptor to a file pointer


2. What is I/O

Input/output is the process of copying data between the primary and external devices.
Device> memory (input operation)
Memory-> device (output Operation)
Advanced I/O
The standard I/O library provided by ansi c is called Advanced I/O, also known as I/O with buffer
Low-level I/O
It is also known as I/O without buffering.


3. Close file opening

Open System Call 1:

Function prototype
Int open (const char * path, int flags );
Parameters
Path: file name, which can contain (absolute and relative) paths
Flags: file opening Mode
Return Value:
If the file is successfully opened, the file descriptor is returned. If the file fails to be opened,-1 is returned.


Open System Call 2:

Function prototype
Int open (const char * path, int flags, mode_t mode );
Parameters
Path: file name, which can contain (absolute and relative) paths
Flags: file opening Mode
Mode: Specifies the access permissions of the owner of the file, the user group of the file, and other users in the system.
Return Value:
If the file is successfully opened, the file descriptor is returned. If the file fails to be opened,-1 is returned.


How to open a file:

O_rdonly open a file for reading
O_wronly open a file for writing
O_rdwr open a file that can be read and written.
All data written by o_append will be appended to the end of the file.
O_creat open the file. If the file does not exist, create the file.
If o_excl has been set to o_creat and the file exists, force open () to fail.
O_trunc clears the file content during open ().


Access permission:

S_irusr
S_iwusr The Write Permission bit of the file owner
S_ixusr file owner's execution permission limit
S_irwxu s_irusr | s_iwusr | s_ixusr
S_irgrp
S_iwgrp file user group write permission bit
S_ixgrp file user group execution permission limit
S_irwxg s_irgrp | s_iwgrp | s_ixgrp
S_iroth
S_iwoth file write permission bit of other users
S_ixoth File Execution permission limit for other users
S_irwxo s_iroth | s_iwoth | s_ixoth


To reuse the file descriptor, call the close () system to release the opened file descriptor.
Function prototype: int close (int fd );
Function parameters:
FD: file descriptor of the file to be closed
Return Value:
If an error occurs,-1 is returned. If the call is successful, 0 is returned.


The example program is as follows:

C ++ code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*************************************** **********************************
> File name: file_oper.c
> Author: Simba
> Mail: dameng34@163.com
> Created time: sat 23 Feb 2013 02:34:02 pm CST
**************************************** ********************************/
# Include <sys/types. h>
# Include <sys/STAT. h>
# Include <unistd. h>
# Include <fcntl. h>
# Include <stdio. h>
# Include <stdlib. h>
# Include <errno. h>
# Include <string. h>

// # Define err_exit (m) (perror (M), exit (exit_failure ))
# Define err_exit (m )\
Do {\
Perror (m );\
Exit (exit_failure );\
} While (0)

/* Fileno: converts a file pointer to a file descriptor.
* Fdopen: converts a file descriptor to a file pointer.
*/
Int main (void)
{
Printf ("fileno (stdin) = % d \ n", fileno (stdin ));

Int FD;
/* FD = open ("test.txt", o_rdonly );

If (FD =-1 ){
// Perror ("Open error ");
Fprintf (stderr, "Open error with errno = % d: % s \ n", errno, strerror (errno ));
Exit (exit_failure );
}
*/
/*
If (FD =-1)
Err_exit ("Open error ");
Printf ("Open success. \ n ");
*/
Umask (0); // do not inherit the umask value of shell, reset to 0; newmode = mode &~ Umask
FD = open ("test.txt", o_wronly | o_creat, 0666 );
If (FD =-1)
Err_exit ("Open error ");
Printf ("Open success. \ n ");
Close (FD );

Return 0;
}


Output:

Fileno (stdin) = 0
Open success.


It should be noted that some system call functions used in Linux system programming generally return-1 if they fail and the global variable errno is set to a specific error code, which can be printed using perror, or print the error message through strerror (errno.

Reference: apue

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.