【C语言】文件指针与文件位置指针,位置指针相关操作库函数

来源:互联网 发布:时间戳判断今天明天js 编辑:程序博客网 时间:2024/04/28 21:57
1 文件指针文件指针是指向一个文件的指针,确切的将是指向用文件这个结构体所定义的对象的起始地址,文件指针的移动是指在文件之间来移动,比如:FILE * fp;fp = fopen("/programe/test.txt","a+");fp就表示文件指针。问题:文件指针能不能在文件之间来回移动?如果能的话,需要先释放文件指针吗?如果不能的话,是为什么,是因为这个指针是指针常量吗?解答:简单程序进行测试:[html] view plain copy #include #include int main() { FILE * fp; fp = fopen("/program/Demo.c","a+"); if(fp == NULL) { return -1; } fprintf(fp,"hello world:Demo.c"); fp = fopen("/program/getcharDemo.c","a+"); if(fp == NULL) { return -1; } fprintf(fp,"hello world:getcharDemo.c"); fclose(fp); 一个指针先后指向两个不同的值,运行结果和程序预想的完全一致,在Demo.c和getcharDemo.c中的最后一行都分别输出了相应的值。说明在这一点上面文件指针和普通的指针是一致的。2 文件位置指针文件位置指针是指文件打开之后,在文件内部进行移动的指针。其数据类型是 fpos_t在MSDN上面是这样说的:fpos_t (long integer, __int64, or structure, depending on the target platform)依据平台架构可能是long型也可能是struct型copyright 1993-1999 by sunmicrosystem这样说:typedef long fpos_ttypedef long long __longlong_t;typedef __longlong_t fpos_t经过32位Linux平台上面编码测试发现它的大小是 12个字节。这个pos_t的结构里面应该至少有一个字段表示的是距离文件起始位置的偏移量。C library reference中定义的文件位置指针的操作函数有以下这些:1 获取文件位置指针当前的位置。 int fgetpos(FILE *stream, fpos_t *pos); int fsetpos(FILE *stream, const fpos_t *pos); 移动文件位置指针: long int ftell(FILE *stream); int fseek(FILE *stream, long int offset, int whence);2 在函数执行过程中移动文件位置指针:size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);3 long int ftell(FILE *stream);获取当前位置到文件开头的字符数4 void rewind(FILE *stream); 文件位置指针返回到文件开头5 int fgetc(FILE *stream); int fputc(int char, FILE *stream);6 char *fgets(char *str, int n, FILE *stream); int fputs(const char *str, FILE *stream);fgets和fputs系列函数也在读完当前行之后,会把文件位置指针指向下一行的开始处。
0 0