1.EOF
代表-1,在文本中会被解析为减号和1两个字符,或更精确地说成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.获取二进制文件的大小
- 函数fseek,用以控制、调整文件指针的值,从而改变下一次读写操作的位置
- 函数原型:int fseek(FILE * fp, long offset, int startPos);
- fp是文件指针,startPos是起始点,offset是目标位置相对起始点的偏移量,正数表示正向偏移(向右),负数表示负向(向左)偏移,如果函数操作执行成功,文件位置指针将被设定为“起始点+offset”,起始点并不是任意设定的,C语言给出了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"); }