1、所用的主要函数接口
open函数
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
返回值:成功返回新分配的文件描述符,出错返回-1并设置error
mode对应open函数来说,仅当创建新文件时才使用第三个参数
read函数
#include <unistd.h>
ssize_t read(int feleds, void *buff, size_t nbytes);
read函数从当前文件偏移量处读入指定的文件内容
read函数会把参数feleds所指的文件传送nbytes个字节到buff中
返回值:返回读到的字节数。若已到文件尾为0,若出错为-1.
如果read成功,则返回读到的字节数。如已到文件末尾,则返回0。
write函数
#include <unistd.h>
ssize_t write(int feleds, const void *buff, size_t nbytes);
write函数会把buff所指的内存写入nbytes个字节到feleds所指的文件中。
返回值:若成功返回写的字节数,出错返回-1。
2、例子
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
int main()
{
int fd = open("1.txt", O_RDONLY);
if(fd == -1)
{
perror("open error");
exit(1);
}
int fd1 = open("newfile.txt", O_CREAT | O_WRONLY, 0644);
if(fd1 == -1)
{
perror("open1");
exit(1);
}
char buf[2 * 1024] = {0};
ssize_t n = read(fd, buf, sizeof(buf));
if(n == -1)
{
perror("read");
exit(1);
}
while(n > 0)
{
ssize_t m = write(fd1, buf, sizeof(buf));
printf("write bytes %d\n", m);
n = read(fd, buf, sizeof(buf));
}
return 0;
}