Linux/Code/io.c

67 lines
1.9 KiB
C
Raw Permalink Normal View History

2025-05-27 16:41:18 +08:00
/****************************************************************
*****************************************************************
/home/xk/origin.txt文件和一个copy.txt文件
origin.txt文件中写入一些数据
*****************************************************************/
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main()
{
int open_status;
int read_status;
int write_status;
int close_status;
char buf[256] = {0};
//1、打开源文件
open_status = open("/home/xk/origin.txt", O_RDWR);
if(open_status == -1)
printf("打开源文件失败\n");
else
printf("打开源文件成功\n");
//2、拷贝源文件数据
read_status = read(open_status, buf, sizeof(buf) - 1);
if(read_status > 0)
printf("已复制源文件内容为:%s", buf);
else
return -1;
//3、关闭源文件
close_status = close(open_status);
if(close_status == 0)
printf("关闭源文件成功\n\n");
else
printf("关闭源文件失败\n\n");
//4、打开目标文件
open_status = open("/home/xk/copy.txt", O_RDWR);
if(open_status == -1)
printf("打开目标文件失败\n");
else
printf("打开目标文件成功\n");
//5、写入数据到目标文件
write_status = write(open_status, buf, strlen(buf));
if(write_status > 0)
printf("复制成功,有%d个字符\n", write_status);
else
return -1;
//6、关闭目标文件
close_status = close(open_status);
if(close_status == 0)
printf("关闭目标文件成功\n");
else
printf("关闭目标文件失败\n");
return 0;
}