C指標編程之道,指標編程之道
//指向檔案類型的指標
//在C語言的檔案你的讀寫一般使用系統的庫函數來對資料進行讀寫
//檔案的類型的指標
//檔案的結構
#include <iostream>
#include <cstdio>
using namespace std;
typedef struct
{
short level; //緩衝區滿或者是空的程度
unsigned flags;//檔案狀態標誌
char fd; //檔案描述符
unsigned hold;//如無緩衝區不讀取字元
short basize; //緩衝區的大小
unsigned char *buffer;//資料緩衝區的位置
unsigned char *curp;//指標當前的指向
unsigned istemp;//臨時檔案
short token; //用於有效性的檢查
}FILE;
//指向檔案的指標
FILE *fp;
//例如下面的例子
//輸入一個字元並且顯示在螢幕
#include <stdio.h>
int main()
{
char ch = getchar();
putchar();
return 0;
}
//scanf()函數原型是
//int scanf(char const *format...);
//
//putchar()函數
//原型是
//int putchar(int character)
//例子
#include <stdio.h>
int main()
{
char ch = 'a';
puchar(ch); //輸出字元a
putchar('\n');
putchar('abc');//只輸出一個字元
putchar('\101');//輸出字元'A'
putchar('\015');//輸出斷行符號,不換行,使游標當前位置移到本行的開頭
putchar('\'');//輸出單引號字元
return 0;
}
//檔案加工場
//功能 ===== //函數
//開啟或關閉 fopen(),fclose();
//讀寫字元 fgetc(),fputc();
//讀寫字串 fgets(),fputs();
//按資料區塊讀寫 fread(),fwrite()
//格式化讀寫 fscanf(),fprintf()
//檔案定位 fseek(),rewind(),ftell()
//判斷檔案是否結束 feof();
//
//應用舉例:
#include <iostream>
#include <cstdio>
using namespace std;
int main(int argc, char *argv[])
{
//判斷參數個數
if(argc != 3)
{
printf("the number of arguments not correct!\n");
exit(1);
}
FILE *fpr, *fpw;
//開啟源檔案
if((fpr = fopen(argv[1], 'r')) == NULL)
{
printf("open source file error!");
exit(1);
}
//開啟目標檔案
if((fpw = fopen(argv[2], 'w')) == NULL)
{
printf("open destination file error!");
exit(1);
}
char ch;
//複製源檔案到目標檔案,每次讀寫一個字元
while((ch = fget(fpr)) != EOF)
{
fputc(ch, fpw);
}
//關閉源檔案,目標檔案
fclose(fpr);
fclose(fpw);
return 0;
}
//合并兩個已經按照遞增排序的順序的整數檔案成為一個按遞增的檔案排序的檔案
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
FILE *fp1;
FILE *fp2;
FILE *fp3;
int t1, t2;
if(agrc != 4)
{
printf("The number of arguments not correct!\n");
exit(1);
}
if((fp1 = fopen(argv[1], "r")) == NULL)
{
printf("open source file1 error\n");
exit(1);
}
if((fp2 = fopen(argv[2], "r")) == NULL)
{
printf("open source file2 error\n");
exit(1);
}
if((fp3 = fopen(argv[3], "r")) == NULL)
{
printf("open source file3 error\n");
exit(1);
}
fread(&t1, sizeof(int), 1, fp1);
fread(&t2, sizeof(int), 2, fp2);
while(! feof(fp1) && !feof(fp2))
{
if(t1 < t2)
{
fwrite(&t1.sizeof(int), 1, fp3);
fread(&t1, sizeof(int), 1, fp);
}
else
{
fwriter(&t2, sizeof(int), 1, fp3);
fwriter(&t2, sizeof(int), 1, fp2);
}
}
while(! feof(fp1))
{
fwrite(&t1.sizeof(int), 1, fp3);
fwrite(&t1,sizeof(int), 1, fp1);
}
while(!feof(fp2))
{
fwrite(&t2, sizeof(int), 1, fp3);
fwrite(&t2, sizeof(int), 1, fp2);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}