您的位置:首页 > 编程语言 > C语言/C++

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

2013-04-02 15:46 288 查看
1 文件指针文件指针是指向一个文件的指针,确切的将是指向用文件这个结构体所定义的对象的起始地址,文件指针的移动是指在文件之间来移动,比如:FILE * fp;fp = fopen("/programe/test.txt","a+");fp就表示文件指针。问题:文件指针能不能在文件之间来回移动?如果能的话,需要先释放文件指针吗?如果不能的话,是为什么,是因为这个指针是指针常量吗?解答:简单程序进行测试:
#include <stdio.h>
#include <stdlib.h>

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[code], 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系列函数也在读完当前行之后,会把文件位置指针指向下一行的开始处。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: