|
发表于 2022-2-23 12:05:22
|
显示全部楼层
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <time.h>
- // CR:Carriage Return,对应ASCII中转义字符\r,表示回车
- // LF:Linefeed,对应ASCII中转义字符\n,表示换行
- // CRLF:Carriage Return & Linefeed,\r\n,表示回车并换行
- // 众所周知,
- // Windows操作系统采用两个字符来进行换行,即CRLF;
- // Unix/Linux/Mac OS X操作系统采用单个字符LF来进行换行;
- // 另外,MacIntosh操作系统(即早期的Mac操作系统)采用单个字符CR来进行换行。
- int main() {
- FILE *file1 = fopen("原文件.txt", "rb");
- FILE *file2 = fopen("新文件.txt", "wb+");
- if(!file1 || !file2) {
- perror("");
- return -1;
- }
- //char buf[1024] = "";
- char buf[1024]; // 不需要初始化吧?
- while(fgets(buf, sizeof(buf), file1) != NULL) //获取有效信息
- {
- // printf("[%s]\n",buf); // 打印显示乱码 ,将txt文本编码改成 ANSI
- for(int i = 0; buf[i] != '\0'; i++) {
- if(buf[i] == ':') //将有效信息存入 新文件
- {
- // fputs()可以指定输出的文件流,不会输出多余的字符;puts()只能向
- // stdout 输出字符串,而且会在最后自动增加换行符。
- //int n = fputs(buf, file2); // 这是在做什么?
- }
- }
- }
- // fflush 强行将缓冲中的数据同步到硬盘上去
- // fflush(file2);
- // fclose 文件关闭前,会自动将缓冲中数据同步到硬盘
- fclose(file2);
- // 下面的代码没法看了,因为没看懂上面的代码,上面的代码在做什么?
- // 把代码删减一下,突出你的问题
- //file2 = NULL;
- file2 = fopen("新文件.txt", "rb");
- if(!file2) {
- perror("");
- return -1;
- }
- // 文件加密
- // 0000 0000 0100 1100 << 4
- // 0000 0100 1100 0000 | 1000 0000 0000 0000 将数字全置为负数
- // 1000 0100 1100 0000 + 0000~1111(0-15)
- // 1000 0100 1100 0110
- char ch = 0;
- srand(time(NULL));
- FILE *file3 = fopen("加密文件.txt", "w+");
- while(1) {
- ch = fgetc(file2);
- if(!feof(file2)) {
- short tmp = (short)ch;
- tmp = tmp << 4;
- // printf("%d\n",tmp);
- tmp = tmp | 0x8000;
- // printf("%d\n",tmp);
- tmp = tmp + rand() % 16;
- // printf("%d\n",tmp);
- fprintf(file3, "%hd", tmp);
- } else
- break;
- }
- fclose(file3);
- file3 = NULL;
- //---------------------------------------------------------------------
- //文件解密
- // 1000 0100 1100 0110 << 1
- // 0000 1001 1000 1100 >> 5
- // 0000 0000 0100 1100
- file3 = fopen("加密文件.txt", "r");
- if(!file3) {
- perror("");
- return -1;
- }
- FILE *file4 = fopen("解密文件.txt", "w");
- if(!file4) {
- perror("");
- return -1;
- }
- while(!feof(file3)) {
- short tmp;
- fscanf(file3, "%hd", &tmp);
- tmp = tmp << 1;
- tmp = tmp >> 5;
- ch = (char)tmp;
- printf("%c", ch);
- fputc(ch, file4);
- }
- fclose(file4);
- file4 = NULL;
- //--------------------------------------------------------------------------
- // 查询信息
- char newbuf[1024] = " ";
- while(1) {
- printf("请输入你要查询的内容(退出查询请输入2):");
- fgets(newbuf, sizeof(newbuf), stdin);
- newbuf[strlen(newbuf) - 1] = '\0';
- // printf("[%s]",newbuf);
- int i = 1;
- fseek(file2, 0, SEEK_SET);
- if(newbuf[0] == '2') {
- break;
- }
- while(fgets(buf, sizeof(buf), file2) != NULL) {
- if(!strncmp(newbuf, buf, strlen(newbuf))) {
- i = 0;
- printf("%s", (char *)buf + strlen(newbuf) + 1);
- break;
- }
- }
- if(i) printf("抱歉,未查询到!\n");
- }
- fclose(file1);
- fclose(file2);
- //system("pause"); // 不是所有编译环境都能用这个
- return 0;
- }
复制代码 |
|