1.用fread实现,将任意文件中的数据显示到终端上。
#include <stdio.h>
int main(int argc, const char *argv[])
{
if(argc < 2)
{
printf("请传参\n");
return -1;
}
FILE* fp = fopen(argv[1],"r");
char c;
int re=0;
while( fread(&c,1,sizeof(c),fp) > 0 )
{
printf("%c",c);
}
putchar(10);
fclose(fp);
return 0;
}
2.用read和write实现文件拷贝。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
int op = open("./test.txt",O_RDONLY,0775);
if(op < 0)
{
perror("op");
return -1;
}
printf("op=%d\n",op);
int op_w = open("./copy_readwrite.txt",O_WRONLY|O_CREAT|O_TRUNC,0775);
if(op < 0)
{
perror("op");
return -1;
}
printf("op_w=%d\n",op_w);
// ssize_t t=0;
char c;
while( read(op,&c,sizeof(c)) > 0 )
{
write(op_w,&c,sizeof(c));
}
int reop,reop_w;
reop = close(op);
if(reop < 0)
{
perror("reop");
return -1;
}
close(op_w);
if(reop_w < 0)
{
perror("reop_w");
return -1;
}
return 0;
}