read_write函数读写文件
vi read_write.c 创建一个.c 文件
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unisted.h>
int main(){
//打开一个已经存在的文件
int fd = open("english.txt", O_RDONLY);
if(fd == 1){
perror("open");
exit(1);
}
//创建一个新文件 -- 写操作
int fd1 = open("newfile", O_CREAT | O_WRONLY, 0664);
if(fd == 1){
perror("open");
exit(1);
}
//read file
char buf[2048] = {0};
//返回值-1代表读文件失败 返回值0代表文件读完了 大于0就是读出来的字节数
int count = read(fd, buf, sizeof(buf));
if(fd == 1){
perror("open");
exit(1);
}
while(count){
//将读出的数据写入另一个文件中
int ret = write(fd1, buf, count);
printf("write bytes %d\n", ret);
//继续读文件
count = read(fd, buf, sizeof(buf));
}
//close file
close(fd);
close(fd1);
}
gcc read_write.c -o readwrite 编译.c文件
./readwite
ls -l newfile english.txt 这时候发现两个文件一样大 证明写的没有问题
lseek
功能:
1.获取文件大小
2.移动文件指针
3.文件扩展
用lseek函数做一个文件的扩展
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include