I/O programming for Linux files
Introduction to files and file descriptors in Linux
- In Linux, operations on directories and pens are equivalent to operations on files
- There are four main types of files in Linux: ordinary files, directory files, connection files and device files
- Under Linux, all operations on devices and files are performed using file descriptors
- The startup of a process is generally accompanied by the opening of three files: standard input (STDIN_FILENO), standard output (STDOUT_FILENO), and standard error (STDERR_FILENO)
Basic I/O operation functions --> without buffering:
open、read、write、lseek以及close
open and close functions
- The open function is used to open or create a file, and attributes can be specified at the same time
- The close function is used to close an open file
Syntax format:
头文件: #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<unistd.h>
open function:
int open(const char *pathname, flags, int perms); pathname:被打开的文件名(可包含路径) flag(打开方式):(常用方式) O_RDONLY:只读方式 O_WRONLY:可写方式 O_RDWR:读写方式 O_CREATE:如果文件不存在,就创建一个新的文件,并用第三个参数为其设置权限 -------------------------------- O_EXCL:用于测试文件是否存在 O_TRUNC:如果文件已经存在,并且以只读或只写成功打开,那么会先全部删除文件中原有数据 O+APPEND:以添加的方式打开文件,打开时,文件指针指向文件的末尾 perms:被打开文件的存取权限,为8禁止表示法 flag参数可以通过"|"连接多个组合形式 返回值: 成功返回文件描述符,失败返回-1
close function:
int close(int fd); fd:文件描述符 返回值: 成功返回0,失败返回-1
Such as: mathod_01.c
#include <sys/types.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> int main(void){ int fd; //定义文件描述符 //调用open函数,以可读写的方式打开,使用“|”符号链接 if((fd=open("/home/my/myTest.c", O_CREATE | O_TRUNC | O_RDWR, 0666)) < 0){ perror("open:"); //打印出错信息 exit(1); }else{ //注意:open函数返回的文件描述符一定是最小的未用文件描述符 printf("Open file:myTest.c %d\n", fd); } if(close(fd) <0){ perror("close:"); exit(1); }else{ printf("Close myTest.c\n"); } exit(0); }
read, write and lseek functions
- Function role:
- read: read data from the specified file descriptor
- write: used to write data to the open file, the write operation starts from the current displacement of the file, and returns failure if it exceeds
- lseek: used to locate the file pointer to the corresponding position in the specified file descriptor
Syntax format:
head File
#include<unistd.h> #include<sys/types.h>
read function
ssize_t read(int fd, void *buf, size_t count); fd:文件描述符 buf:指定存储器读出数据的缓冲区 count:指定读出的字节数 返回值:成功返回读到的字节数;0表示读到文件尾;-1表示出错
write function
ssize_t write(int fd, void *buf, size_t count); fd:文件描述符 buf:指定存储器写入数据的缓冲区 count:指定写入的字节数 返回值:成功,返回已写字节数;失败,返回-1
lseek function
off_t lseek(int fd, off_t offset, int whence); fd:文件描述符 offset:偏移量,每一读写操作所需要移动的距离,单位是字节的数量。可正(前移)可负(后移) whence(当前位置的基点): SEEK_SET:当前位置为文件的开头,新位置为便宜量的大小 SEEK_CUR:当前位置为文件指针的位置,新位置为当前位置加上偏移量 SEEK_END:当前位置为文件的结尾,新位置为文件的大小加上偏移量的大小 返回值:成功,返回当前位移;失败返回-1
- Function role:
Such as: method_02.c
#include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #define MAXSIZE int main(void){ int i, fd, size, len; char *buf = "Hello! Welcom to Linux World!"; char buf_read[10]; len = strlen(buf); //打开文件并制定权限 if((fd = open("/home/my/myTest.c", O_CREAT | O_TRUNC | O_RDWR, 666)) < 0 ){ perror("Open:"); exit(1); }else{ printf("open file:myTest.c\n", fd); } //write函数将buf中的内容写入到打开的文件中 if((size = write(fd, buf, len)) < 0){ perror("write:"); exit(1); }else{ printf("Write:%s\n", buf); } //调用lseek函数移动指针,并调用read读取文件 lseek(fd, 0, SEEK_SET); if((size = read(fd, buf_read, 10)) < 0){ perror("read:"); exit(0); }else{ printf("read from file:%s\n", buf_read); } //关闭close() if(close(fd) < 0){ perror("close:"); exit(1); }else{ printf("Close myTest.c\n"); } exit(0); }
fcntl function: Manipulate the characteristics of file descriptors
function format
head File
#include <sys/types.h> #include <unistd.h> #include <fcntl.h>
Function prototype:
int fcntl(int fd, int cmd, struct flock *lock); fd:文件描述符 cmd:(常见的有以下几个) F_DUPFD:复制文件描述符 F_GETFL:得到open设置的标志 F_SETFL:改变open设置的标志 F_GETTFK:根据lock描述,决定是否上文件锁 F_SETFK:设置lock描述的文件锁 F_SETOWN:设置进程号或进程组号 lock:设置记录锁的具体状态 lock的结构: struct flock{ short l_type; //取值:F_RDLCK(读取锁→共享锁)、F_WRLCK(写入锁→排斥锁)、F_UNLCK(解锁) short l_start; //相对位移量(字节) short l_whence; off_t l_len; //加锁区域长度 pid_t l_pid; } 返回值:成功,返回0,;失败返回-1
Standard I/O Development -> Buffer Based
- Purpose:
Reduce the number of calls using read and write - Three types of buffer storage:
- Full buffering The actual I/O operation takes place
when the standard I/O buffer is filled. - Line Buffering The standard I/O library performs I/O operations
when input and output have new line characters. - No buffering
No of characters, e.g. to display error messages as quickly as possible
- Full buffering The actual I/O operation takes place
Open and close files
- Open file standard functions: fopen, fdopen, freopen, return a pointer to FILE
- fopen: specify the path and mode to open the file
- fdopen: Specifies that the opened file description matches the pattern
- freopen: You can specify the open file, mode, and specify a specific IO stream
function format definition
head File
#include<stdio.h>
fopen、fdopen、freopen
FILE* fopen(const char* path, const char* mode); FILE* fdopen(int fd, const char* mode); FILE* freopen(const char* path, const char* mode, FILE* stream); path:包含要打开的文件的路径及文件名 fd:要打开的文件描述符 mode:文件打开状态,取值: r/rb:打开只读文件,文件必须存在 r+/r+b:打开可读写文件,文件必须存在 w/wb:打开只写文件,覆盖的方式(会清空存在的文件内容) w+/w+b:打开可读写文件,覆盖的方式 a/ab:附加的当时打开只写文件,添加方式(在文件内容后添加内容) a+/a+b:附加的当时打开读写文件,添加方式 stream:已打开的文件指针 返回值:成功,返回指向FILE的指针,失败返回NULL
Close the file function: fclose
- Function: Write the data in the buffer to the file and release the file resources
Format:
int fclose(FILE* stream); stream:已打开的文件指针 返回值:成功:0,失败:EOF
Such as:
#include<stdio.h> int main(void){ FILE *fp; //调用fopen函数 fp = fopen("/home/test/hello.c", "w"); if(fp != NULL){ printf("Open Success!"); } //关闭文件指针 fclose(fp); }
- Open file standard functions: fopen, fdopen, freopen, return a pointer to FILE
file read and write
head File:
#include <stdio.h>
Read file: fread function
Format:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); ptr:存放读入记录的缓冲区 size:读取的记录大小 nmemb:读取的记录数 stream:要读取的文件流 返回值:成功,返回实际读到的nmemb,失败返回EOF
Write file: fwrite function
Format
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream); ptr:存放写入记录的缓冲区 size:写入的记录大小 nmemb:写入的记录数 stream:要写入的文件流 返回值:成功,返回实际写入的nmemb数目,失败返回EOF
Such as:
#include <stdio.h> int main(void){ FILE *stream; char str[5] = {'H', 'e', 'l', 'l', 'o'}; //先打开文件 stream = fopen("test", "w"); int number = fwrite(str, sizeof(char), nmemb, stream); printf("number = %d", number); //关闭文件流 fclose(stream); }