Read ()/write ()/pread ()/pwrite () and so on __ network programming

Source: Internet
Author: User
Tags fread stdin

There are a lot of input and output functions in Linux and UNIX, and sometimes it really makes the rookie who wants to have a little bit of a relationship at their wits ' end. First to see what functions, through the analysis and summary, to see if we can make these functions have a rational understanding, oh, it is so, even if I did not waste this leisure.

Kernel file i/o-> standard library i/o-> Advanced I/O->IPC

1. Read ()/write ();

2. Pread ()/pwrite ();

3. GETC ()/PUTC ();

4. FGETC ()/FPUTC ();

5. GetChar ()/putchar ();

6. Ferror ()/feof ();

7. Fgets ()/fputs ();

8. Gets ()/puts ();

9. Fread ()/fwrite ();

scanf ()/fscanf ()/sscanf ()/vscanf ()/vfscanf ()/vsscanf ()

printf ()/fprintf ()/sprintf ()/snprintf ()/vprintf ()/vfprintf () ()/vsprintf ()/vsanprintf ()

Readv ()/writev ()

Read ()/written ()

MSGRCV ()/msgsnd ()

REVC ()/recvfrom ()/recvmsg ()

Send ()/sendto ()/sendmsg ()

RECV_FD ()/send_fd ()/send_err ()

A rough summary of the next, as shown above the 17 categories, I see, it really makes the head a little dizzy. But the Masters have said that there is a reasonable, below let us see, is how the simple, so that these functions have the reason for existence. To understand this, you first need to know what logical processing modules the system is going through in the input and output. The following illustration

The above user-space applications use system calls to complete the read-write process of the file, as described below:

(1) User space and kernel space; This group of relationships is not to mention clear.

(2) Read and write: All CPU or memory or user program as the main body, then read, memory <-file; write, memory-> file; Because the subject is the user program, so read or write is, to read, to determine from what read, to write, to what to write.

(3) The Application system service has three ways: direct implementation through shell command, using library function, direct call to system call functions, such as read,write and other commands. Here you can see the relationship between the library function and the system call. System call is the most basic, any want to get the system services to go through it, this is a checkpoint.

(4) file I/O and standard I/O: The former refers to the user space does not need in fact the process explicitly provide a buffer (such as the BF2), in fact, the process in user space directly call the Read/write functions, but, in the kernel space are to have a buffer. This is generally referred to as file I/O. Standard I/O: Provides a buffered interface for functions that do not buffer I/O, which can be used for I/O functions that do not buffer, or with buffered I/O functions. This is generally the library function in the user space established (these buffers are completed by the library function, do not need the user management, is encapsulated in the library function), such as BUF2, may be the library function to be received from the top of the data to do a preprocessing, such as format transformation. Using standard I/O functions eliminates the need to worry about choosing the best buffer size (which is done for you by the library function), and one that simplifies the processing of input rows. The standard I/O function library provides functions that enable us to control the buffering style used by the library.

(5) Buf1/buf2/buf3:buf1, is actually the user space some string, the variable and so on, understands as the data can. Sometimes it is also defined as the form of a name buf, such as Char Buf[maxline], but at this point buf is simply a name called BUF, which distinguishes it from the concept of a true buffer. BUF2, this is the library function for you to build the old in user space, without you personally management, you just command, such as calling a function in a library function, it is for you to serve, this BUF2, we call the real buffer. BUF3, whether you choose File I/O form or standard I/O form, regardless of which, in the kernel of the buffer BUF3 (this is unavoidable), but this also do not user to pro-Pro, by the kernel on behalf of management.

(6) Stream: This is the standard for I/O, the stream is the logical representation of the file, the file I/O: Process->fd-> file, change to: Process->FP (File object)-> Stream/Buffer-> file. The original operation on the file, now the user only use processing: Process-> Flow between the operation, and flow-> file between the operation will be completed by the library function for you. The logical representation of the stream is the file object, and the stream's entity is the buffer used by the stream, which is the representative of the file relative to the application process. Stream =file + buffer. The standard I/O library provides buffering by minimizing the number of read and write writes.

OK, let's do the above four points, and then add it when you have ideas. Below to get to the point, look at the above functions, what form, why have these functions exist, all for the system to do what, how to do.

1. File I/O related (process->fd-> file) (file fd, BUF):

(1) Read ()

Form: #include <unistd.h>

ssize_t Read (int filedes, void *buf, size_t nbytes);

Success: Returns the number of bytes read; Error: return-1; end of file: returns 0;

Reason: Basic system call function;

Implementation: File (referred to by filedes)-Read nbytes byte-> memory buf.

Supplemental: There are several situations in which the actual number of bytes read is less than the number of bytes required to read:

When read from a normal file, the end of the file is reached before the requested byte count is read.

When you read from a terminal device, you usually read at most one line at a time.

When read from the network, the buffering mechanism on the network may cause the return value to be less than the number of bytes required to read.

When reading from a pipe or FIFO, if the pipe contains less than the required number of bytes, return only the actual

The number of bytes.

When read from certain device-oriented devices, a maximum of one record is returned at a time.

When a signal is interrupted and a partial amount of data has been read.

The read operation begins at the current offset of the file, and the offset increases the number of bytes actually read before it is successfully returned. The Common UNIX system shell provides a way to open a file on standard input and to trace or rewrite a file on standard output, which makes it unnecessary for the program to open the input and output files itself.

(2) write ()

Form: #include <unistd.h>

ssize_t write (int filedes, const void *buf, size_t nbytes);

Success: Returns the number of bytes written; Error: return-1;

Reason: Basic system call function;

Implementation: File (indicated by filedes) <-write nbytes byte-memory buf.

Added: A common reason for write errors 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 the O_append option 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.

(3) Pread ()

Form: #include <unistd.h>

ssize_t pread (int filedes, void *buf, size_t nbytes, off_t offset);

Success: Returns the number of bytes read; Error: return-1; To end of file: return 0

Reason: Because the kernel may temporarily suspend the process between the Lseek and the read calls, the synchronization problem is caused, and the invocation pread corresponds to the Lseek and read in order, which is equivalent to a bundle of atomic operations.

Implementation: File (referred to by filedes)-Read nbytes byte-> memory buf.

Add: When calling Pread, you cannot break its positioning and read operations, and the file pointer is not updated.

(4) Pwrite ()

Form: #include <unistd.h>

ssize_t pwrite (int filedes, const void *buf, size_t nbytes, off_t offset);

Success: Returns the number of bytes written; Error: return-1;

Reason: Because the kernel may temporarily suspend the process between Lseek and write calls, the synchronization problem is caused, and the invocation pwrite corresponds to the Lseek and write sequences called, which are equivalent to a bundle of atomic operations.

Implementation: File (indicated by filedes) <-write nbytes byte-memory buf.

Add: When calling Pwrite, you cannot break its positioning and read operations, and the file pointer is not updated.

2. Flow (stream) or standard I/O (Process->fp-> stream (file+ buffer)-> file) (memory buf, stream FP):

Enter one character at a time:

(1) getc ();

Format: #include <stdio.h>

int getc (FILE *fp);

Success: Returns the next character; error: returns EOF; end of file: EOF;

Implementation: Memory <-read a character C-stream (the stream referred to by FP, is the logical representation of the file)

Reason: In standard I/O, the stream is considered a logical representation of the file, and the operation of the process-> file is converted to the process-> stream (that is, the file).

Add: When the function returns the next character, it converts its unsigned char type to an int type. The reason for unsigned is that if the highest bit is 1, the return value is not negative. The reason for reshaping the return value is to return all possible character values plus an indication that an error has occurred or has reached the end of the file. That is, the character value becomes a positive int value, and the negative value is an error or reaches the end of the file. (A negative table has a special meaning), and all three functions return the same value-1, whether it's an error or the end of the file. Because each stream maintains two flags in the file object-the error flag and the file end flag-You must call ferror or feof to differentiate between them.

(2) fgetc ();

Format: #include <stdio.h>

int fgetc (FILE *fp);

Success: Returns the next character; error: returns EOF; end of file: EOF;

Implementation: Same GETC

Reason: Same getc

Add: Same getc

(3) GetChar ();

Format: #include <stdio.h>

int GetChar (void);

Success: Returns the next character; error: returns EOF; end of file: EOF;

Implementation: Memory <-reads a character C-stream (the stream referred to by stdin, is the logical representation of the standard input file), so Getchar=getc (stdin);

Reason: Same getc

Add: Same getc

Enter one line at a time:

(4) fgets ();

Format: #include <stdio.h>

Char *fgets (char *restrict buf, Int N, FILE *restrict FP);

Success: return BUF; error: return null; End of file: NULL;

Implementation: Memory BUF <-takes one line of characters from the stream referred to in FP-stream (referred by FP)

Reason: In standard I/O, the stream is considered a logical representation of the file, and the operation of the process-> file is converted to the process-> stream (that is, the file).

Supplemental: The length of the user process buffer must be specified n, that is, the size of the BUF, which reads from the stream until the next newline character, but not more than n-1 characters, and the read characters are sent into the user buffer buf. The buffer ends with a null character. If the line includes the last newline character is greater than n-1, it returns only an incomplete row, but the buffer buf always ends with a null character, and calls to this function continue to read the row. The contents of the buffer buf are: (character + newline characters) +null. So character + line break <=n-1, because must leave a null character to identify the end of the buffer;

(5) gets ();

Format: #include <stdio.h>

Char *gets (char * buf);

Success: return BUF; error: return null; End of file: NULL;

Implementation: Memory BUF <-takes 1 lines of characters from the stream that stdin refers to-standard input stream (indicated by Fp=stdin)

Reason: ditto;

Supplemental: Deprecated, the problem is that when using gets, the caller cannot specify the length of the buffer buf (user process), which can cause a buffer overflow.

Output one character at a time:

(6) PUTC ();

Format: #include <stdio.h>

int PUTC (int c, FILE *FP);

Success: return C; Error: return EOF;

Implementation: In-memory shape variable C-letter c-> stream (referred by FP). As to when the stream will be written in C file, this is implemented by the library function, without the user worry;

Reason:

Add:

(7) FPUTC ();

Format: #include <stdio.h>

int FPUTC (int c, FILE *FP);

Success: return C; Error: return EOF;

Implementation: In-memory shape variable C-letter c-> stream (referred by FP). As to when the stream will be written in C file, this is implemented by the library function, without the user worry;

Reason:

Add:

(8) Putchar ();

Format: #include <stdio.h>

int Putchar (int c);

Success: return C; Error: return EOF;

Implementation: In-memory shape variable C-letter c-> stream (indicated by fp=stdout). As to when the stream will write C to the standard output file, this by the library function to implement, do not worry about users;

Reason:

Add: Putchar (c) =PUTC (c,stdout);

Output one line at a time:

(9) fputs ();

Format: #include <stdio.h>

int fputs (const char *restrict str, FILE *restrict FP);

Success: return non-negative; error: return EOF;

Implementation: An in-memory character array str-the str-> stream (indicated by FP).

Reason:

Add: A string terminated with a null character (equivalent to user space buf, definitely null, corresponding to fgets BUF must have a null to identify the end of the buffer buf. Writes to the specified stream, and the Terminator at the end of NULL is not written into the stream. Note that this does not necessarily have to be one row at a time, because it does not require a newline character before null, there is a buf, there is no, usually, before the null character is a line break, but it is not always the case. User space buf: character (+ newline character) +null, buf in stream: Character + line break.

(a) puts ();

Format: #include <stdio.h>

int puts (const char * str);

Success: return non-negative; error: return EOF;

Implementation: An in-memory character array str-the str-> standard output stream (indicated by fp=stdout).

Reason:

Add: Writes a null-terminated string to the standard output, equivalent to a process-> Stream-> Standard output file. The Terminator does not write, but puts then writes a newline character to the standard output. Should be used sparingly, lest it be remembered whether it added a newline character at the end. and Fgets and fputs in the process of line breaks, in a pragmatic manner, there are, no, no, not in the user buf and stream buffers and files themselves add, only in the data flow buffer, increase or filter to null characters. When fgets, a null is added to the user buf to identify the end of the user buf, while fputs null as the terminating character, but the null at the end is not written in the stream.

Binary I/o:

(one) fread ()

Format: #include <stdio.h>

ssize_t fread (void *restrict ptr, size_t size, size_t nobj, FILE *restrict FP);

Success: The number of objects read.

Implementation: Memory Start ptr<-read n objects-stream (referred by FP)

Reason: The above one character or one line of the way I/O operation, when we read or write a structure, for one character at a time, you must loop through the entire structure, each loop processing a byte, read or write a byte, this will be annoying. For one row, the fputs stops when there is a null character in each structure, so it cannot be used to implement the read structure, and the fgets contains null bytes or newline characters that do not work properly. So to and implement the structure as a whole read or write.

Add: The basic problem with binary is that it can only be used to read data that has been written on the same system. Its original

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.