zoukankan      html  css  js  c++  java
  • linux以字符为单位进行读写操作

    1 所用函数

      fgetc(FILE *fp):成功返回所读入的字符 失败为-1

      fputc(int c,FILE *fp):第一个参数表示需要输出的字符 第二个参数表示输出的文件。成功返回输出的字符 失败返回-1

    2 实现类似cp命令的复制程序,复制文件的同时输出该文件到屏幕 命令的格式copy src des(./a.out test1.txt test2)

    3 实现

     1 #include <stdio.h>
     2 #include <errno.h>
     3 #include <unistd.h>
     4 #include <stdlib.h>
     5 int main(int argc, char *argv[ ])
     6 {
     7     FILE *fp1, *fp2; /* 源文件和目标文件 */
     8     int c;
     9     if(argc != 3){ /* 检查参数个数 */
    10         printf("wrong command
    ");
    11         exit(1);
    12     }
    13     if((fp1 = fopen(argv[1], "r")) == NULL){ /* 打开源文件 */
    14         perror("fail to open");
    15         exit(1);
    16     }
    17     if((fp2 = fopen(argv[2], "w+")) == NULL){ /* 打开目标文件 */
    18         perror("fail to open");
    19         exit(1);
    20     }
    21     /* 开始复制文件,每次读写一个字符 */
    22     while((c = fgetc(fp1)) != EOF){ /* 读源文件,直到将文件内容全部读完 */
    23         if(fputc(c, fp2) == EOF){ /* 将读入的字符写到目标文件中去 */
    24             perror("fail to write");
    25             exit(1);
    26         }
    27         if(fputc(c, stdout) == EOF){ /* 将读入的字符输出到屏幕 */
    28             perror("fail to write");
    29             exit(1);
    30         }
    31     }
    32     if(errno != 0){ /* 如果errno变量不为0说明出错了 */
    33         perror("fail to read");
    34         exit(1);
    35     }
    36     fclose(fp1); /* 关闭源文件和目标文件 */
    37     fclose(fp2);
    38     return 0;
    39 }

    4 截图

  • 相关阅读:
    POJ1845 数论 二分快速取余
    CentOS6.5下安装wine
    Centos 6.5中安装后不能打开emacs的问题
    vim编辑器的设置文件
    centos无线网卡设置
    FreeBSD简单配置SSH并用root远程登陆方法
    在CentOS/RHEL 6.5上安装Chromium 谷歌浏览器
    Centos中安装Sublime编辑器
    强连通分量!
    强连通分量
  • 原文地址:https://www.cnblogs.com/lanjianhappy/p/7193331.html
Copyright © 2011-2022 走看看