1、写入(write)
头文件
#include <unistd.h>
函数原型
ssize_t write(int fd, const void *buf, size_t count);
参数:
int fd :文件描述符
const void *buf :字节缓冲区,buf为要写入的字符串,(buf为void的指针)
size_t count:文件描述符写入字符串的大小
write:在缓冲区buf中取count个字节写入到文件描述符fd指向的文件里面
返回值
写入成功:返回一个整型数,大小就是写入的字节个数
写入失败:返回 -1
例如
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd;
char* buf = "hello world!";
fd = open("./file2",O_RDWR); //先打开文件
if(fd == -1){ //没有就创建文件
printf("open file fail\n");
fd = open("./file2",O_RDWR | O_CREAT,0600); //创建文件
if(fd > 0){ //表示成功创建文件
printf("creat success\n");
}
}
printf("creat file2 success %d\n",fd);
write(fd,buf,strlen(buf)); //将字符串buf写入到fd指向的文件中,大小为字符串的大小
close(fd); //注意要关闭文件
return 0;
}
file2中
首先通过open函数打开文件file2,发现没有file2,打印了 open file fail 然后创建了一个file2文件,打印 creat success ,再将file2的文件描述符打印出来,可以看到file2 的文件描述符为非负整数 3 ,说明创建成功,最后成功的将buf中的数据写入到file2中。
2、读出(read)
头文件和write一样
#include <unistd.h>
函数原型
ssize_t read(int fd, void *buf, size_t count);
参数:
int fd :文件描述符
const void *buf :字节缓冲区,buf为要读入的字符串,(buf为void的指针)
size_t count:读出字符串的大小
read:将文件描述符 fd 指向的文件读取count个字节放入字节缓冲区 buf 中
返回值
读出成功:返回一个整型数,大小就是读出的字节个数
读出失败:返回 -1
例如
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char* buf = "hello world!";
char* readBuf = NULL;
fd = open("./file2",O_RDWR);
printf("creat file2 success %d\n",fd);
int n_write = write(fd,buf,strlen(buf));
printf("write %d\n",n_write); //打印写入到file2的字节个数
close(fd); //关闭文件
fd = open("./file2",O_RDWR); //重新打开,让光标回到头,不然读不到数据
readBuf = (char*)malloc(sizeof(char) * n_write); //为readBuf开辟空间
int n_read = read(fd,readBuf,n_write); //fd指向的文件读到readBuf中
printf("readNum %d n_read = %s\n",n_read,readBuf); //打印读取到的字节个数和读到的数据
close(fd);
return 0;
}
因为上面写操作已将将file2文件创建了,所以下面直接打开重新写入,在这里应该要注意这两条代码
close(fd); //关闭文件
fd = open("./file2",O_RDWR); //重新打开,让光标回到头,不然读不到数据
这是关于光标移动的问题,可参考光标移动(lseek)