文件IO
程序1:open
#include <stdio.h>//标准IO的头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
//1.打开文件
int fd1 = open("./1.txt",O_RDWR);
int fd2 = open("./2.txt",O_RDWR);
printf("fd1=%d fd2=%d\n",fd1,fd2);
//2.对文件进行读操作
//2.1定义一个存放数据的空间
char buf[10]={0}; //初始化并清空buf
read(fd1,buf,sizeof(buf));
printf("%s\n",buf);
//3.打开之后,记得关闭文件
close(fd1);
close(fd2);
}
程序2:read和write
#include <stdio.h>//标准IO的头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main()
{
//1.打开文件
int fd1 = open("./1.txt",O_RDWR);
int fd2 = open("./2.txt",O_RDWR);
//printf("fd1=%d fd2=%d\n",fd1,fd2);
//2.对文件进行读操作
//2.1定义一个存放数据的空间
char buf[20]={0}; //初始化并清空buf
while(1)
{
memset(buf,0,sizeof(buf));//内存重置函数
ssize_t n = read(fd1,buf,sizeof(buf)-1);
printf("%s",buf);
if(n == 0)
{
break;
}
}
char w_buf[20] = "hello world";
write(fd2,w_buf,strlen(w_buf));
//3.打开之后,记得关闭文件
close(fd1);
close(fd2);
}
程序3:copy
#include <stdio.h>//标准IO的头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main()
{
//1.打开文件
int fd1 = open("./1.txt",O_RDWR);
int fd2 = open("./2.txt",O_RDWR);
//printf("fd1=%d fd2=%d\n",fd1,fd2);
//2.对文件进行读操作
//2.1定义一个存放数据的空间
char buf[100]={0}; //初始化并清空buf
while(1)
{
memset(buf,0,sizeof(buf));//内存重置函数
ssize_t n = read(fd1,buf,sizeof(buf)-1);//9
write(fd2,buf,strlen(buf));
printf("%s",buf);
if(n == 0)//9<10
{
break;
}
}
//3.打开之后,记得关闭文件
close(fd1);
close(fd2);
}
程序4:mycat
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
//打开文件
//read并打印buf内容
//关闭文件
//for循环打开文件,argc,argv[]
//while循环读和打印
//关闭
int main(int argc,char *argv[])
{
if(argv < 2)
return -1;
int fd = open(argv[1],O_RDONLY);
if(fd <0)
{
perror("打开文件失败\n");
return -1;
}
char buf[100];
int n;
while(1)
{
bzero(buf,sizeof(buf));
n = read(fd,buf,sizeof(buf));
if(n <= 0)
break;
printf("%s",buf);
}
close(fd);
return 0;
}
程序5:mycopy
#include <stdio.h>//标准IO的头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int main(int argc,char **argv)
{
//argc存的是参数的个数
printf("argc=%d\n",argc);
if(argc != 3)
{
printf("只需要两个参数\n");
return -1;
}
//argv存的是参数的字符串形式
//argv[0] ./a.out
//argv[1] 1.txt
//argv[2] 2.txt
//argv[3] 3.txt
//把第一个参数复制到第二个参数
int fd1 = open(argv[1], O_RDWR);//如果参数里出现了O_CREAT,
//那就需要多填一个mode_t类型的文件权限
if(-1 == fd1)
{
printf("打开%s失败,错误为%s\n",argv[1],strerror(errno));
}
int fd2 = open(argv[2], O_RDWR | O_CREAT,0777);
if(-1 == fd2)
{
printf("打开%s失败,错误为%s\n",argv[2],strerror(errno));
}
char buf[100];
while(1)
{
memset(buf,0,100);
int ret = read(fd1,buf,sizeof(buf)-1);
write(fd2,buf,strlen(buf));
if(0 == ret)
{
break;
}
}
close(fd1);
close(fd2);
}