关于FILE结构在VC6中有如下定义:
#ifndef _FILE_DEFINED struct _iobuf { char *_ptr; //文件输入的下一个位置 int _cnt; //当前缓冲区的相对位置 char *_base; //指基础位置(即是文件的起始位置) int _flag; //文件标志 int _file; //文件描述符id int _charbuf; //检查缓冲区状况,如果无缓冲区则不读取 int _bufsiz; //文件缓冲区大小 char *_tmpfname; //临时文件名 };
typedef struct _iobuf FILE; #define _FILE_DEFINED #endif#include <stdio.h> #include <stdlib.h> void main() { char ch = 0; int temp= 0; FILE *fp,fp1; if((fp=fopen(".\\1.txt","a"))==NULL) { printf("cannot open the file"); exit(0); }if((fp1=fopen(".\\1.txt","r"))==NULL) { printf("cannot open the file"); exit(0); }fscanf(fp,"%d",&temp);
fprintf(fp,"%d\t",temp);fclose(fp),flcose(fp1); }
代码运行结果是将1.txt文件的第一个数据追加到该文件的最后。下面介绍一下,只读方式“r”和追加方式“a”的区别,如图:
fp 是追加打开文件返回的指针,其base只有刚被复制的temp的值。
fp1是只读打开文件返回的指针,其base指向文件数据的首地址。可以看到文件内容为:11,80....
从图上可以看出:
base后的内容并没有变化。
其内容添加是在fclose(fp);中完成的。调用fclose()函数之前,需要压栈保存当前指针位置。然后调用fclose(00401190)
在fclose代码段中,继续调用call __flush (00403e30)
在 _flush (00403e30)中调用_write (0040cba0)完成数据的添加