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

亦凉 2022-06-16 08:25 338阅读 0赞

1 文件指针

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

比如:

FILE * fp;

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

fp就表示文件指针。

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

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

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

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

[html] view plain copy

print ?

  1. #include
  2. #include
  3. int main()
  4. {
  5. FILE * fp;
  6. fp = fopen(“/program/Demo.c”,”a+”);
  7. if(fp == NULL)
  8. {
  9. return -1;
  10. }
  11. fprintf(fp,”hello world:Demo.c”);
  12. fp = fopen(“/program/getcharDemo.c”,”a+”);
  13. if(fp == NULL)
  14. {
  15. return -1;
  16. }
  17. fprintf(fp,”hello world:getcharDemo.c”);
  18. fclose(fp);

save_snippets.png

一个指针先后指向两个不同的值,运行结果和程序预想的完全一致,在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 intoffset, int whence);

2 在函数执行过程中移动文件位置指针:

size_t fread(void *ptr, size_tsize, 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, intn, FILE *stream);

int fputs(const char *str, FILE *stream);

fgets和fputs系列函数也在读完当前行之后,会把文件位置指针指向下一行的开始处。

发表评论

表情:
评论列表 (有 0 条评论,338人围观)

还没有评论,来说两句吧...

相关阅读

    相关 【C语言】文件位置指针

    1、计算机为每个文件保留一个整数,这个整数表示下一次文件读写操作开始的位置(所以每次读取文件读到的是不一样的) 2、这个位置一定在两个相邻字节之间 3、这个整数的数值就是文

    相关 python 文件指针

    f = open('‪C:\\Users\ldh\Desktop\test.txt','r') 以只读方式打开一个文件,获取文件句柄,如果是读的话,r可以不写,默认就是