将任意文件中的数据打印到终端上
#include <stdio.h>int main(int argc, const char *argv[])
{if(argc < 2){printf("文件名未输入,请输入文件名!\n");return -1;}//打开文件FILE* fo = fopen(argv[1],"r");if(fo == NULL){perror("fopen");return -1;}//将任意文件中的数据打印到终端上char data;while(fread(&data, 1, sizeof(data), fo) == sizeof(data)){printf("%c", data);}//关闭文件fclose(fo); return 0;
}
用read和口write实现文件拷贝
#include <stdio.h>#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>// 用read和口write实现文件拷贝;
int main(int argc, const char *argv[])
{int fo = open(argv[1], O_RDONLY);if(fo < 0){perror("open");return -1;}printf("fo = %d\n", fo);//需要拷贝的文件int fo2 = open(argv[2], O_WRONLY);if(fo2 < 0){perror("open");return -1;}ssize_t res;char str[100];//循环读取文件中的数据while(1){bzero(str, sizeof(str));res = read(fo, str, sizeof(str));//判断read的返回值if(res == 0){printf("文件读取完毕!\n");break;}else if(res < 0){perror("read");break;}//写入文件write(fo2, str, res);}//关闭文件if( close(fo) < 0 && close(fo2) < 0 ){perror("close");return -1;}return 0;
}