zoukankan      html  css  js  c++  java
  • C 读写文件以及简单的文件加密

    温习了下文件的读写操作

    做下笔记

    1》首先是读文件:

    1.在对应的文件夹创建 D:\test\myTest.txt文件,且输入自己待测试的文字内容。

    2.读的代码如下,就会打印出myTest的文件的内容。

    int main()
    {
        char *path = "D:\test\myTest.txt";
    
        FILE *fp = fopen(path, "r");
    
        char buff[500];
        while (fgets(buff, 50, fp))
        {
            printf("%s", buff);
        }
    
        fclose(fp);
        system("pause");
        return 0;
    }

    2》写文件

    比较好理解,直接贴代码

    int main() {
        char *path = "D:\test\myTest_write.txt";
        FILE *fp = fopen(path, "w");
        if (fp == NULL) {
            printf("文件操作失败,直接return");
            return 0;
        }
        char *text = "hello world";
        fputs(text, fp);
        fclose(fp);
        system("pause");
        return 0;
    }

    3》读写非文本文件(读二进制文件)

    int main() {
        char * read_path = "D:\test\myTest.jpg";
        char * write_path = "D:\test\myTest_write.jpg";
        //
        FILE * read_fp = fopen(read_path, "rb");//注意传入的属性值
        //写(实际上就是复制一份)
        FILE * write_fp = fopen(write_path, "wb");
        char buff[50];
        int len = 0;
        while ((len = fread(buff, sizeof(char), 50, read_fp)) != 0)
        {
            fwrite(buff, sizeof(char), len, write_fp);
        }
        fclose(read_fp);
        fclose(write_fp);
        system("pause");
        return 0;
    }

    看了上面,是不是有一点点小成就了呢?都可以读取任意的文件的内容了

    额,没感觉到啥啊。那说明你要好好思考如何举一反三了。

    可读可写,是不是就意味着可以对文件的数据进行操作,让别人看不了文件内容呢?

    答案是肯定的,那就可以写一个简单的文件加密程序吧。

    直接贴成果:

    加密解密方法:

    void myEncodeAnDecode(char prePath[], char resultPath[], int password) {
        FILE * normal_fp = fopen(prePath, "rb");
        FILE * encode_fp = fopen(resultPath, "wb");
        
        int ch;
        while ((ch = fgetc(normal_fp)) != EOF){
            fputc(ch ^ password, encode_fp);
        }
        fclose(normal_fp);
        fclose(encode_fp);
    }

    然后看应用:

    int main() {
        char * oriPath = "D:\picLibrary\xiaoHuangTu.png";//原文件,加密后可删除掉,防止别人查看
        char * showOthersPath = "D:\picLibrary\xiaoHuangEncode.png";//存放加密的文件,给别人看,别人也看不了的文件
        char * newPath = "D:\picLibrary\xiaoHuangDecode.png";//将加密的文件解密出来的文件,可以自己偷偷的查看
    
        //加密
        myEncodeAnDecode(oriPath, showOthersPath, 100);//密码随便搞个100
        //解密
        myEncodeAnDecode(showOthersPath, newPath, 100);
        system("pause");
        return 0;
    }

    这就是一个简单的文件夹解密的核心程序。不妨可以自己去试试,将自己的私密照片视频啥的加密。是不是666呢?

  • 相关阅读:
    2单表CRUD综合样例开发教程
    1代码表样例开发教程
    ProcessOn
    UniEAP Platform V5.0 Unable to compile class for JSP
    Message Unable to compile class for JSP
    UniEAP Platform V5.0建库
    UML_2_浅谈UML的概念和模型之UML九种图
    PPT鼠绘必须掌握的PPT绘图三大核心功能
    PPT添加节
    remap.config文件配置模板
  • 原文地址:https://www.cnblogs.com/bokezhilu/p/7620477.html
Copyright © 2011-2022 走看看