示例
//Visual Studio中加上这句才可以使用scanf()
//否则只能使用scanf_s()
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//malloc()、free()
#include <stdlib.h>
#include <time.h>
#include <math.h>
// DOS文本文件中的文件结尾标记
#define CNTL_Z '\032'
#define SLEN 81
//argc: 参数个数 argv[]: 参数数组
//int main(int argc, char **argv)
int main(int argc, char *argv[])
{
char file[SLEN];
char ch;
FILE *fp;
long count, last;
puts("Enter the name of the file to be processed:");
scanf("%80s", file);
if ((fp = fopen(file, "rb")) == NULL)
{
printf("reverse can't open %s\n", file);
exit(EXIT_FAILURE);
}
/*
fseek(参数1, 参数2,参数2):
参数2
该参数表示从起点(即,第3个参数)开始要移动的距离,
该参数必须是一个long类型的值,可以为正(前移)、
负(后移)或0(保持不动)。
fseek(fp, 0L, SEEK_SET);//定位至文件开始处
fseek(fp, 10L, SEEK_SET);//定位至文件中的第10个字节
fseek(fp, 2L, SEEK_CUR);//从文件当前位置前移2个字节
fseek(fp, 0L, SEEK_END);//定位至文件结尾
fseep(fp, -10L, SEEK_END);//从文件结尾处回退10个字节
参数3: 根据ANSI标准,模式常量定义在stdio.h头文件中
SEEK_SET: 文件开始处
SEEK_CUR: 当前位置
SEEK_END: 文件末尾
旧的实现可能缺少这些定义,可以使用数值0L、1L、2L分别表示这3种模式。
或者,实现可能把这些明示常量定义在别的头文件中。如果不确定,请查阅手册。
*/
int result = fseek(fp, 0L, SEEK_END); //定位到文件末尾
if (0 != result)
{
printf("fseek failure.");
}
//ftell()返回当前位置,此函数适用于二进制模式打开文件。
//返回从文件开始处到文件结尾的字节数
last = ftell(fp);
for (count = 1L; count <= last; count++)
{
//从文件结尾处往前读取文件内容,所以第2个参数传负值
fseek(fp, -count, SEEK_END);//回退
ch = getc(fp);//从文件中读取一个字符
if (ch != CNTL_Z && ch != '\r') //MS-DOS文件
putchar(ch);
}
putchar('\n');
fclose(fp);
system("pause");
return 0;
}