文件IO函数
1.用read和write实现文件拷贝
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char *argv[])
{
if(argc<2)
{
printf("请输入文件名!\n");
return-1;
}
int fd1 = open(argv[1],O_RDONLY);
int fd2 = open("./copy.txt",O_WRONLY | O_CREAT | O_TRUNC,0777);
char str[100]="";
ssize_t res;
while(1)
{
bzero(str,sizeof(str));
res = read(fd1,str,sizeof(char));
if(0 == res)
{
printf("文件读取完毕!\n");
break;
}
else if(res < 0)
{
perror("read");
break;
}
write(fd2,str,res);
}
if(close(fd1)<0)
{
perror("close");
return -1;
}
return 0;
}
运行结果:
2.用fread实现将任意文件中的数据显示在终端上
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
if(argc<2)
{
printf("请在终端输入文件名!\n");
return -1;
}
FILE* fp = fopen(argv[1],"r");
if(NULL == fopen)
{
perror("fopen");
return -1;
}
char c;
while((fread(&c,1,sizeof(c),fp))!=0)
{
printf("%c",c);
}
fclose(fp);
return 0;
}
运行结果:
原文地址:https://blog.csdn.net/Volimteczh/article/details/136354173
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!