第一章Linux标准IO编程

来源:互联网 发布:linux 怎么重启mysql 编辑:程序博客网 时间:2024/05/21 18:36

源码来自华清远见的书上例子

一.实例一

     mycp_1.c

#include <stdio.h>#include <string.h>#include <errno.h>int main(int argc, char *argv[]){FILE *fps, *fpd;int c;if (argc < 3){printf("Usage : %s <src_file> <dst_file>\n", argv[0]);return -1;}if ((fps = fopen(argv[1], "r")) == NULL){printf("fail to open %s : %s\n", argv[1], strerror(errno));return -1;}if ((fpd = fopen(argv[2], "w")) == NULL){printf("fail to open %s : %s\n", argv[2], strerror(errno));return -1;}while ((c = fgetc(fps)) != EOF){fputc(c, fpd);}fclose(fps);fclose(fpd);return 0;}


 

二.实例二

     mycp_2.c

#include <stdio.h>#include <string.h>#include <errno.h>#define N 64int main(int argc, char *argv[]){FILE *fps, *fpd;char buf[N];if (argc < 3){printf("Usage : %s <src_file> <dst_file>\n", argv[0]);return -1;}if ((fps = fopen(argv[1], "r")) == NULL){printf("fail to open %s : %s\n", argv[1], strerror(errno));return -1;}if ((fpd = fopen(argv[2], "w")) == NULL){printf("fail to open %s : %s\n", argv[2], strerror(errno));return -1;}while (fgets(buf, N, fps) != NULL){fputs(buf, fpd);}fclose(fps);fclose(fpd);return 0;}


 

三.实例三

      mycp_3.c

#include <stdio.h>#include <string.h>#include <errno.h>#define N 64int main(int argc, char *argv[]){FILE *fps, *fpd;char buf[N];int n;if (argc < 3){printf("Usage : %s <src_file> <dst_file>\n", argv[0]);return -1;}if ((fps = fopen(argv[1], "r")) == NULL){printf("fail to open %s : %s\n", argv[1], strerror(errno));return -1;}if ((fpd = fopen(argv[2], "w")) == NULL){printf("fail to open %s : %s\n", argv[2], strerror(errno));return -1;}while ((n = fread(buf, 1, N, fps)) > 0){fwrite(buf, 1, n, fpd);}fclose(fps);fclose(fpd);return 0;}


四.实例四

          timer_record

#include <stdio.h>#include <unistd.h>#include <time.h>#include <string.h>#define N 64int main(int argc, char *argv[]){FILE *fp;time_t t;struct tm *tp;char buf[N];int line = 0;if (argc < 2){printf("Usage : %s <file>\n", argv[0]);return -1;}if ((fp = fopen(argv[1], "a+")) == NULL){perror("fail to fopen");return -1;}while (fgets(buf, N, fp) != NULL){if (buf[strlen(buf)-1] == '\n') line++;}while ( 1 ){time(&t);tp = localtime(&t);fprintf(fp, "%d, %d-%d-%d %d:%d:%d\n", ++line, tp->tm_year+1900, tp->tm_mon+1,   tp->tm_mday, tp->tm_hour, tp->tm_min, tp->tm_sec);fflush(fp);sleep(1);}return 0;}


 

 

 

0 0