本文主要是介绍[IO] fread,read,write的实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.用fread 实现,将任意文件中的数据显示到终端上
#include <stdio.h>int main(int argc, const char *argv[])
{FILE* fp = fopen(argv[1],"r");if(NULL == fp){perror("fopen");return -1;}char arr[1024];size_t br;while((br = fread(arr,1,sizeof(arr),fp))>0){for(size_t i=0;i<br;i++){printf("%c",arr[i]);}}fclose(fp);return 0;
}
2.用read和write实现文件拷贝
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>int main(int argc, const char *argv[])
{umask(0);int fd = open(argv[1],O_RDONLY);int wr = open(argv[2],O_WRONLY);if(fd < 0){perror("open");return -1;}printf("fd=%d\n",fd);ssize_t res;char buf[128] = "";while(1){bzero(buf,sizeof(buf));res = read(fd,buf,sizeof(buf));if(0 == res){printf("文件读取完毕\n");break;}else if(res<0){perror("read");break;}write(wr,buf,res);}if(close(fd)<0){perror("close");return -1;}return 0;
}
这篇关于[IO] fread,read,write的实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!