调用系统函数进行文件的读写
打开文件:
int open(const char* pathname,int flags);
int open(const char* pathname,int flags,mode_t mode); //mode:当打开的文件不存在时,就要在打开文件的同时并创建文件,那么就需要设定文件的权限.
flags:打开文件的选项:若同时需要多种操作时,就可以将多个选项进行或运算.
O_WRONLY:只写打开
O_RDONLY:只读打开
O_RDWR:读写打开
O_CREAT:创建
写文件:
ssize_t write(int fd, const void *buf, size_t count);
若写入成功,返回写入的字节数.
若失败,返回-1.
返回0:对于普通文件没什么影响,而对于特殊文件有影响.
读文件:
ssize_t read(int fd, void *buf, size_t count);
若返回值大于零表示读取成功,并且返回值就是读取的字节数.
若返回值等于0,表示文件已经读完(当读一个空文件时就会返回0).
若返回值小于0,表示文件读失败.
下面是一个简单的例子:先写入文件,再从文件中读取.
1 #include<stdio.h>
2 #include<unistd.h>
3 #include<sys/types.h>
4 #include<sys/stat.h>
5 #include<fcntl.h>
6 #include<string.h>
7
8 int main()
9 {
10 int fd = open("text.txt",O_WRONLY|O_CREAT,0666);
11 if(fd == -1)
12 {
13 perror("open");
14 return 1;
15 }
16 const char* str = "You are breautiful.\n";
17 int count = 5;
18 while(count--)
19 {
20 write(fd,str,strlen(str));
21 }
22 close(fd);