1.EOF
在C语言中,或更精确地说成C标准函数库中表示文件结束符(end of file)。在这种以EOF作为文件结束标志的文件,必须是文本文件。在文本文件中,数据都是以字符的ASCII代码值的形式存放。我们知道,ASCII代码值的范围是0~127,不可能出现-1,因此可以用EOF作为文件结束标志。
2.函数feof
函数原型: int feof(FILE *fp)
功能:判断文件是否结束
返回值:文件结束,返回真(非0),文件未结束,返回0
3.实例
- 非密码加密 txt
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> void jia(char *path,char *newpath) { FILE *pfr = fopen(path, "r"); FILE *pfw = fopen(newpath, "w"); char ch = 0; while (ch != EOF) //EOF 文件结束 { ch = fgetc(pfr);//读取,EOF if (ch != EOF) { ch += 1; fputc(ch, pfw); } } fclose(pfr); fclose(pfw); } void jie(char *path, char* newpath) { FILE *pfr = fopen(path, "r"); FILE *pfw = fopen(newpath, "w"); char ch = 0; while (ch != EOF) //EOF 文件结束 { ch = fgetc(pfr);//读取,EOF if (ch != EOF) { ch -= 1; fputc(ch, pfw); } } fclose(pfr); fclose(pfw); } void main() { char *path = "C:\\Users\\sjx\\Desktop\\test\\Q.txt"; char *pathjia = "C:\\Users\\sjx\\Desktop\\test\\Qjia.txt"; char *pathjie = "C:\\Users\\sjx\\Desktop\\test\\Qjie.txt"; jia(path, pathjia); jie(pathjia, pathjie);//路径 system("pause"); } system("pause"); }
- 根据密码加密 (二进制文件加密解密)
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> char *path = "C:\\Users\\sjx\\Desktop\\test\\Q.exe"; char *pathjia = "C:\\Users\\sjx\\Desktop\\test\\Qjia.exe"; char *pathjie = "C:\\Users\\sjx\\Desktop\\test\\Qjie.exe"; void run(char *path, char *newpath) { FILE *pfr = fopen(path, "rb"); FILE *pfw = fopen(newpath, "wb"); if (pfr==NULL || pfw ==NULL) { return; } else { char ch; while (!feof(pfr)) { char ch = fgetc(pfr); char newch = ch ^ 3; fputc(newch, pfw); } fclose(pfr); fclose(pfw); } } void main() { run(path, pathjia); run(pathjia, pathjie); /*printf("%d", getfilesizeseek(path));*/ system("pause"); }
3.获取二进制文件的大小
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> char *path = "C:\\Users\\sjx\\Desktop\\test\\Q.exe"; char *pathjia = "C:\\Users\\sjx\\Desktop\\test\\Qjia.exe"; char *pathjie = "C:\\Users\\sjx\\Desktop\\test\\Qjie.exe"; int getfilesize(char *path) { int i = -1; FILE *pfr = fopen(path, "rb"); if (pfr == NULL ) { return -1; } else { while (!feof(pfr)) { char ch=fgetc(pfr); i++;//读取一个字符,前进一次 } fclose(pfr); return i; } } int getfilesizeseek(char *path) { FILE *pfr = fopen(path, "rb"); if (pfr == NULL) { return -1; } else { fseek(pfr, 0, SEEK_END);//文件指针移动末尾 int length = ftell(pfr);//获取当前文件指针距离开头的长度 fclose(pfr); return length; } } int main() { run(path, pathjia); run(pathjia, pathjie); /*printf("%d", getfilesizeseek(path));*/ system("pause"); }
时间: 2024-10-11 01:46:39