文件指针与文件位置指针,文件位置指针相关的库函数

来源:互联网 发布:sai在mac虚拟机没压感 编辑:程序博客网 时间:2024/06/16 01:00

1 文件指针

文件指针是指向一个文件的指针,确切的是存放了用文件这个结构体所定义的对象的起始地址,文件指针的移动是指在文件之间来移动,

比如:

FILE * fp;

fp = fopen("/programe/test.txt","a+");

fp就表示文件指针。

问题:文件指针能不能在文件之间来回移动?

如果能的话,需要先释放文件指针吗?

如果不能的话,是为什么,是因为这个指针是指针常量吗?

解答:简单程序进行测试:

[html] view plain copy
print?
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3.   
  4. int main()  
  5. {  
  6.   
  7. FILE * fp;  
  8. fp = fopen("/program/Demo.c","a+");  
  9. if(fp == NULL)  
  10. {  
  11.         return -1;  
  12. }  
  13. fprintf(fp,"hello world:Demo.c");  
  14. fp = fopen("/program/getcharDemo.c","a+");  
  15. if(fp == NULL)  
  16. {  
  17.         return -1;  
  18. }  
  19.   
  20. fprintf(fp,"hello world:getcharDemo.c");  
  21. 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_t

typedef    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
原创粉丝点击