1. 程式人生 > >C語言新建檔案,向檔案中輸入內容並讀出檔案內容

C語言新建檔案,向檔案中輸入內容並讀出檔案內容

三、格式化讀寫函式--fscanf( )函式和fprint( )函式 呼叫方式分別是: fscanf(檔案指標,格式字串,輸入表);
fscanf 函式將指標指向的檔案內容,以格式符要求的形式,讀入記憶體指定地址內 fprintf(檔案指標,格式字串,輸出表);fprintf 函式是將記憶體指定地址內的內容,以格式符要求的形式,輸出到指標指向的檔案 說明: 以上兩個函式與scanf( ) 和printf( )函式 只有一點不同:即前二者的讀寫物件是磁碟資料檔案,即是檔案指標指向的磁碟檔案。 用fscanf( )和fprintf( )函式對磁碟檔案 進行讀寫,使用方便,容易理解,但是,由於輸入是要將ASCII碼轉換為二進位制形式,輸出時又要將二進位制形式轉換成字元,花費時間較多。因此,在記憶體與磁碟頻繁交換資料的情況下,最好不用fscanf( )和fprintf( )函式,而用fread和fwrite函式。
例:編制一個程式,建立一個電話簿,包括姓名和電話號碼兩項內容,該程式有增加新姓名和電話號碼的功能,也可以根據姓名查詢已經存入電話簿的電話號碼。 程式在設計時將分別設計成三個函式: 1.選單選項--menu( )
2.增加新電話號碼--add-num( )
3.查詢老電話號碼--lookup( )。
#include<stdio.h>
#include<stdlib.h>
#include <ctype.h>
#include<string.h>
#include<conio.h>
void add_num( ),lookup( );
char menu();




int main( )
{
    char choice;
    do
    {
        choice=menu( );
        switch(choice)
        {
            case 'a':
                add_num( );
                break;
            case 'l':
                lookup( );
                break;
        }
    }while(choice!='q');
    return 0;
}
char menu( )
{
    char ch;
    do{
        printf("(A)dd,(L)ookup or (Q)uit:");
        ch=tolower(getche( ));/*從鍵盤讀取一個數據,小寫字母不做處理,大寫字母轉換成小寫字母*/
        printf("\n");
      }while(ch!='q'&&ch!='a'&&ch!='l');
    return ch;
}
void add_num( )
{
    FILE * fp;
    char name[80];
    int num;
    if((fp=fopen("phone","a"))==NULL)
    {
        printf("cannot open directory file\n");
        exit(1);
    }
    printf("enter name and number:");
    fscanf(stdin,"%s %d",name,&num);/*從輸入流中讀取資料到name和num*/
    fscanf(stdin,"%*c");/*接收鍵盤敲回車後的換行符*/
    fprintf(fp,"%s %d\n",name,num);/*將name和num資訊寫入檔案中*/
    fclose(fp);
}
void lookup( )
{
    FILE *fp;
    char name[80],name2[80];
    int num;
    if((fp=fopen("phone","r"))==NULL)
    {
        printf("cannot open directory file\n");
        exit(1);
    }
    printf("name?");
    gets(name);/*獲取螢幕輸入的字串*/
    while(!feof(fp))/*判斷是否到檔案結尾處*/
    {
        fscanf(fp,"%s%d",name2,&num);/*從檔案中讀取資料到name2和num變數中*/
        if(!strcmp(name,name2))/*比較輸入的字串是否和檔案中的字串相等*/
        {
            printf("%s: %d\n",name,num);
            break;
        }
    }
    fclose(fp);
}






請執行程式,可以得到如下結果:
(A)dd,(L)ookup or (Q)uit:A Enter name and number: Liming 6789 1234 135
(A)dd,(L)ookup or (Q)uit:A Enter name and number: Lihung 5678 235 357
(A)dd,(L)ookup or (Q)uit:L name?Liming Liming:(6789)1234-135 
(A)dd,(L)ookup or (Q)uit:Q
四、讀入整型量函式--- getw( )函式和putw( )函式 呼叫方式如下例:
i=getw(fp);     它的作用是從磁碟檔案讀一個整數到記憶體,賦給整型變數i。
putw(10,fp);    它的作用是將整數10輸出到fp指向的檔案。 五、讀寫字串函式-- fgets( )函式和fputs( )函式 呼叫方式分別為:
fgets(字元陣列,n,fp);
fgets( )函式的作用是將fp指向的檔案中(n-1)個字元讀入字元陣列,並且加結束符“\0”,若在(n-1) 個字元前遇到EOF或換行符,均結束讀入。
fputs(字元陣列,fp);
fputs( )函式的作用是向指定的檔案輸出一個字串。如:fputs(“china”,fp); 說明:fgets( )和fputs( )函式與gets( )和puts( )函式的不同之處也在於:前二者的讀寫物件為指定的檔案。 例子:從鍵盤讀入若干個字串,對它們按照字母順序排序,然後把它們送到磁碟檔案中儲存。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    FILE *fp;
    char str[3][10],temp[10];
    int i,j,k,n=3;

    printf("enter strings:\n");
    for(i=0;i<n;i++)/*將輸入的字串存入字元陣列中*/
        gets(str[i]);

    for(i=0;i<n-1;i++)/*用選擇法對字串進行排序*/
    {
        k=i;
        for(j=i+1;j<n;j++)
            if(strcmp(str[k],str[j])>0)
                k=j;
        if(k!=i)
        {
            strcpy(temp,str[i]);
            strcpy(str[i],str[k]);
            strcpy(str[k],temp);
        }
    }

    if((fp=fopen("string.txt","w"))==NULL)
    {
        printf("cannot open file!\n");
        exit(0);
    }

    for(i=0;i<n;i++)/*將字元陣列中的字串儲存到硬碟的檔案中*/
    {
        fputs(str[i],fp);
        fputs("\n",fp);
    }
    fclose(fp);
    
    printf("save in file:\"string.txt\"\n");
    printf("Read from file\n");
    printf("\nThe new sequence:\n");
    if((fp=fopen("string.txt","r"))==NULL)
    {
        printf("cannot open the file!\n");
        exit(0);
    }
    i=0;
    while(fgets(str[i],10,fp)!=NULL)/*將檔案讀出*/
        printf("%s",str[i++]);
    return 0;
}


 六、使用者自定義讀寫函式 如果使用者對於讀寫盤檔案還有特殊的要求,或者是在某些C編譯的庫函式中,不包括前面所介紹的那些讀寫函式,使用者也可以自己定義函式。 比如:定義getw函式
getw(fp)
{FILE *fp;
char *s; int i;
s=&i;
s[0]=getc(fp); s[1]=getc(fp);
return(i);
}

定義putw函式
putw(i,fp)
{int i;
FILE *fp;
{char *s;
s=&i;
putc(s[0],fp);putc(s[1],fp);
return(i);
}

七、常見的檔案讀、寫錯誤 1. 使用檔案時忘記開啟檔案。用後又忘記關閉檔案,造成檔案的資料丟失。
2. 混淆檔案指標與檔案讀/寫的位置指標的概念。
3. 不明確當前位置指標的位置,造成讀/寫錯誤。
4. 不能使檔案正確定位。
5. 檔案的開啟與使用方式不匹配。
例如,對檔案以只讀方式開啟,卻對檔案進行讀寫,請看程式:
if((fp=fopen(“test”,“r”))==NULL)
{printf(“cannot open this file\n”);
exit(1);
}
ch=fget(fp);
while(ch!=‘#’)
{ch=ch+4;
fputc(ch,fp);
ch=fget(fp);
}

以上程式段的“r”應改作“r+”。