c语言中实现文件内容的复制
思路:
1.先创建一个新文件
2.打开有内容的已存在文件
3.创建一个buf,将旧文件的内容写入buf中
4.再将buf中的内容写入新文件中,写入新文件的过程中,最好使用循环,否则如果buf不够会复制不全。
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include <stdlib.h>
#include<unistd.h>
int main()
{
int fp2 = open("file2", O_RDWR | O_CREAT,0777);/*先创建一个新文件 */
if(fp2 == -1)
{
perror("tips:");/*提示信息 */
}
printf("fp2 = %d\n",fp2);
int fp1 = open("file1",O_RDWR,0777);/*打开已存在的文件 */
if(fp1 == -1)
{
perror("tips:");
exit(1);
}
printf("fp1 = %d\n",fp1);
char buf[2048] = {110};/*创建一个缓冲区 */
int fr = read(fp1,buf,sizeof(buf));
if(fr == -1)
{
perror("tips:");
exit(1);
}
while(fr)/*实现循环写和读操作 */
{
int fw = write(fp2,buf,fr);
printf("fw = %d\n",fw);
fr =read(fp1,buf,sizeof(buf));/*继续下一次读操作*/
}
int fc1 = close(fp1);
int fc2 = close(fp2);/*最后关闭文件*/
printf("fc1 = %d,fc2 = %d\n",fc1,fc2);
}