Summarizing Linux IO file operations tutorial

Source: Internet
Author: User
Tags error code fread function prototype lstat strtok file permissions

1.
For file operations, although they are implemented through function calls, they can be divided into two categories: system calls and library functions.


2.
In Linux, almost everything can be seen as a file.
This means that ordinary programs can use disk files, serial ports, printers, and other devices just as you would with a file (a normal definition)


3.
Library function calls are ultimately implemented through system calls. A library function call is considered to be an optimization of the system's efficiency considerations.


System call actually refers to the bottom of a call, in the Linux design is the meaning of the underlying call. The hardware is facing. The library function call is oriented to the application development, equivalent to the API of the application, there are many reasons for this way, first: double buffering technology implementation. Second, portability. Third, some performance flaws in the underlying call itself. Four: Let the API also have a level and specialized work oriented.


4.
System call
The functions provided by the system call such as open, close, read, write, IOCTL, etc., need to include header file Unistd.h. Take write as an example: its function prototype is size_t write (int fd, const void *buf, size_t nbytes),
(。 The Linux system has 3 file descriptor values assigned by default: 0-standard input,1-standard output,2-standard error. )


System calls are operating system-related, so there is generally no portability across the operating system.


5.
Library function call
Standard C library functions provide file manipulation functions such as fopen, Fread, Fwrite, Fclose, Fflush, fseek, etc., which need to include header file stdio.h. Take fwrite as an example, its function prototype is size_t fwrite (const void *buffer, size_t size, size_t item_num, FILE *PF),
(There is also a corresponding predefined file pointer: Stdin-standard input,stdout-standard output,stderr-standard error.) )
Library function calls are system independent, so portability is good.


6.
A file ID is used for identity files that are unique on the system. The total number of file descriptors is the maximum number of files that the system can open, depending on the configuration of the system.


When you start running the program, which is when the system starts running, it typically has three file descriptors that are already open. They are:
0: Standard input
1: Standard output
2: Standard error
The file descriptor for the other file, which is returned when the calling file opens the function open. This means that each device corresponds to a file descriptor. The file descriptor is assigned by the operating system, with the smallest assigned each time.


---------------------------------------------------------------
7.1
Write writes the data in the buffer to the file. Note that the files here are widely meaningful, such as writing to a disk, writing to a printer, and so on.
function prototype for write () in Linux:
size_t write (int fildes, const void *buf, size_t nbytes);


7.2
The function prototype of read in Linux:
size_t read (int fildes, void *buf, size_t nbytes);


7.3
The function of the system call Open is to turn on a file and return the descriptor for that file.
Simply put, open creates an access path to a file or device. If the operation succeeds, it returns a file descriptor
This file descriptor is unique and will not be shared with any other running processes. If two programs open a file at the same time, you get two different price descriptors. If
At the same time, the operation of two files, their respective operations, complementary effects, covering each other (after written overwrite first) in order to prevent files from being read-write conflict, you can use the function of file locks.


There are two function prototypes for open in Linux:
int open (const char *path, int oflags);
int open (const char *path, int oflags, mode_t mode);


7.4
The close system call is used to "shut down" a file that closes a file descriptor Fildes the association between its files. The file descriptor is freed and can be reused.
Close successfully returned 1, error returned-1.
#Include <unistd.h>
int close (int fildes);


7.5
IOCTL system call
IOCTL provides an interface for controlling the device and its descriptor behavior and configuring the underlying service. Terminals, file descriptors, and even tape drives can be defined for their IOCTL, specifically


Details can refer to the user manual for a particular device.
Here is the IOCTL function prototype
#include <unistd.h>
int ioctl (int fildes, int cmd,,,,,,);
IOCTL the action given in the CMD parameter for the descriptor Fildes the specified object.

7.6
Other system calls related to file management
There are many other system calls that can operate on files.
Several common examples are: Lseek () sets the file descriptor Fildes the read and write pointer to the specified file, that is, it can set the next read/write location of the file.
Fstat,stat,lstat is a function operation related to a file descriptor and is not described here.
DUP,DUP2 system call. DUP provides a way to copy file descriptors so that we can access the same file through two or more different file descriptors. This can be used to
Read and write data at different locations in the file.

---------------------------------------------------------------

8.
The standard I/O library and its header files <stdio.h> provides a common interface for the underlying I/O system calls.
If you need to have explicit control over the behavior of the device, it is best to use the underlying system call, as this avoids some unintended side effects of using library functions, such as input/output buffering.


FILE *fopen (const char *filename, const char *mode);
size_t fread (void *ptr, size_t size, size_t nitems, FILE *stream);
size_t fwrite (const coid *ptr, size_t size, size_t nitimes, FILE *stream);
int fclose (FILE *stream);

The role of the Fflush function is to write out all the data that is not written in the file stream. In efficiency, a data buffer is used when the library function is used, and writes are performed when the buffer is full. Using the Fflush function
You can write out all of the data in the buffer, without worrying about whether the buffer is full. Fclose's execution implicitly invokes the Fflush function, so you do not have to call Fflush before fclose execution.

int fflush (FILE *stream);


Linux Learning IO operations, File IO summary

File IO is not cached, and each read and write invokes the corresponding system call in the kernel.
File IO Common functions:
Open,close,read,write,lseek
For the kernel, all open files have file descriptor references.
The file descriptor is a non-negative integer. When you open an existing file or create a new file, you and the process return a file descriptor.
When a file is read or written, the file descriptor returned with open identifies it and passes it as an argument to read or write.


1.open (file path to be opened), int flag, mode
FALG:O_RDONLY,O_WDONLY,O_RDWR,O_CREAT,O_EXCL (if there is a return error message)
O_trunc (delete the data in the file if it already exists)
2.read (fd,buf,size_t count)
The number of bytes read was successfully returned by the call.
If 0 is returned, the end of the file is reached.
If 1 is returned, an error is indicated, and the error code is set by errno.
3.write ()
4.lseek (fd,offset,whence)

5. Open file directory Opendir ()

6. Get File Property function: This set of functions is quite important.
Stat () Gets a structure of information related to this named file
Fstat () Gets information about the file that has been opened on the descriptor Filedes
Lstat () returns information about the symbolic link, not the file information referenced by the symbolic link

Parameters in the stat structure: St_mode, St_mode is the property description of the file being opened.

s_ifmt:0x070000

Switch (St.st_mode & S_IFMT)//Determine what type of file
{
Case s_ifreg:printf ("-"); Break
Case s_ifdir:printf ("D"); Break
Case s_iflnk:printf ("L"); Break
Case s_ifblk:printf ("B"); Break
Case s_ifchr:printf ("C"); Break
Case s_ififo:printf ("P"); Break
Case s_ifsock:printf ("S"); Break
}

S_ ... is the internal definition of some macros, specific man look at

7.getopt function Check yourself, Getopt's role is to identify characters that begin with "-".

while (ch = getopt (argc, argv, "la"))!= EOF)
{
Switch (CH)
{
Case ' a ':
printf ("Option A is set\n");
Aflag = 1;
Break
Case ' l ':
printf ("option L is set\n");
Lflag = 1;
Break
Default:
printf ("Wrong option%c is set\n", optopt);
}
}

and Getpwuid (ST.ST_UID); Getgrgid (St.st_gid) function, which is to obtain the current user name, the user group name

The 8.strtok () function is the operation that truncates the string. The following example uses a space to truncate.

This function is very strange, the first assignment must be buf, and the first parameter is NULL, this is more disgusting ....

arg[i++] = strtok (buf, "");
Todo
{
arg[i++] = strtok (NULL, "");
}while (Arg[i-1]!= NULL);

9. Functions on Folder operations: DIR *opendir (); struct dirent * Readdir (): There is a pointer inside, you can automatically move the next file in the folder until it is empty

Example: Use them to complete a copy of a file

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

int main (int argc, char **argv)
{
int fd1, FD2;
Char buf[1024];
int nbyte;

if (argc!= 3)
{
printf ("Using:%s srcfilename decfilename\n", argv[0]);
return-1;
}

if ((fd1 = open (argv[1), o_rdonly)) < 0)
{
Perror ("open");
return-1;
}

if (fd2 = open (argv[2), o_wronly| O_creat | O_trunc, 0666)) < 0)
{
Perror ("open");
return-1;
}

while (Nbyte = Read (FD1, buf, sizeof (BUF)) > 0)
{
Write (FD2, buf, nbyte);
}

Close (FD1);
Close (FD2);

return 0;

}

Open file directory Opendir ()

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main (int argc, char **argv)
{
DIR *dir;
struct Dirent *dirent;

dir = Opendir (argv[1]);
while ((dirent = Readdir (dir))!= NULL)
{
printf ("%s\n", dirent->d_name);
}
}

Get File Property function:
Stat () Gets a structure of information related to this named file
Fstat () Gets information about the file that has been opened on the descriptor Filedes
Lstat () returns information about the symbolic link, not the file information referenced by the symbolic link
Using stat to realize the basic function of LS:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <grp.h>
#include <pwd.h>
#include <time.h>

int main (int argc, char **argv)
{
struct STAT st;
int i;
struct passwd *pw;
struct group *gr;
struct TM *tm;
Stat (argv[1], &st);

Switch (St.st_mode & S_IFMT)//Determine what type of file
{
Case s_ifreg:printf ("-"); Break
Case s_ifdir:printf ("D"); Break
Case s_iflnk:printf ("L"); Break
Case s_ifblk:printf ("B"); Break
Case s_ifchr:printf ("C"); Break
Case s_ififo:printf ("P"); Break
Case s_ifsock:printf ("S"); Break
}

for (i = 8; I >= 0; i--)
{
if (St.st_mode & (1 << i))//st.st_mode after 8 digits, determine file permissions
{
Switch (i%3)
{
Case 2:printf ("R"); Break
Case 1:printf ("w"); Break
Case 0:printf ("X"); Break
}
}
Else
printf ("-");
}

PW = Getpwuid (ST.ST_UID);
GR = Getgrgid (St.st_gid);


printf ("%2d%s%s%4ld", St.st_nlink, Pw->pw_name, Gr->gr_name, st.st_size);


TM = LocalTime (&st.st_ctime);
printf ("%04d-%02d-%02d%02d:%02d", Tm->tm_year + 1900, Tm->tm_mon + 1, tm->tm_mday, Tm->tm_hour, tm->tm_ MIN);

printf ("%s\n", argv[1]);

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.