關於文件操作

關於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)完成數據的添加

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章