(1) file descriptor in Linux the legal range of FD is 0 or a positive positive number, it cannot be a negative number.
(2) open to return the FD program must be recorded well, later to this file all operations rely on this FD to correspond to this file, and finally close the file also need FD to specify close this file. If FD had lost it before we closed the file, the file could not be closed or read and write.
Reminder: Real-time man manual search
(1) When we write the application, many API prototypes are impossible to remember, so real-time query, with the man manual
(2) Man 1 xx check linux shell command, man 2 xxx Check API, man 3 XXX Check library function
Read File contents
(1) ssize_t read (int fd, void *buf, size_t count);
FD indicates which file to read, FD is generally returned by the previous open to get BUF is the application itself provides a memory buffer, used to store the read content, Count is the number of bytes we want to read the return value Size_ The t type is a type that the Linux kernel redefined with typedef (in fact, int), and the return value represents the number of bytes successfully read.
Writing to a file
(1) write with write system call, write prototype and understanding method and read Similar
(2) Note that the pointer type of buf is void
(3) Just write 12 bytes, then read out the result read out is 0 (but read out successfully).
1#include <stdio.h>2#include <sys/types.h>3#include <sys/stat.h>4#include <fcntl.h>5#include <unistd.h>6#include <string.h>7 8 9 Ten intMainintargcChar*argv[]) One { A intFD =-1;//FD is the file descriptor, and the filename descriptor - Charbuf[ -] = {0}; - Charwritebuf[ -] ="l Love Linux"; the intRET =-1; - - //First step: Open File -FD = open ("a.txt", O_RDWR);//Note Before you define a a.txt + if(-1= = FD)//sometimes also written as: (FD < 0) - { +printf"File open error \ n"); A } at Else - { -printf"file opened successfully, FD =%d.\n", FD); - } - - //Step Two: Read and write Files in //Write a file -RET =Write (FD, WRITEBUF, strlen (WRITEBUF)); to if(Ret <0) + { -printf"write failed. \ n"); the } * Else $ {Panax Notoginsengprintf"Write succeeded,%d characters were written \ n", ret); - } the /* + //Read file A ret = Read (FD, buf, 5); the if (Ret < 0) + { - printf ("Read failed \ n"); $ } $ Else - { - printf ("actually read%d bytes. \ n", ret); the printf ("File contents are: [%s].\n", buf); - }Wuyi */ the //Step Three: Close the file - Close (FD); Wu - return 0; About}
Linux A simple read-write file