【轉】fread函數和fwrite函數

來源:互聯網
上載者:User

標籤:

1.函數功能

  用來讀寫一個資料區塊。

2.一般調用形式

  fread(buffer,size,count,fp);

  fwrite(buffer,size,count,fp);

3.說明

  (1)buffer:是一個指標,對fread來說,它是讀入資料的存放地址。對fwrite來說,是要輸出資料的地址。

  (2)size:要讀寫的位元組數;

  (3)count:要進行讀寫多少個size位元組的資料項目;

  (4)fp:檔案型指標。

 注意:1 完成次寫操(fwrite())作後必須關閉流(fclose());

           2 完成一次讀操作(fread())後,如果沒有關閉流(fclose()),則指標(FILE * fp)自動向後移動前一次讀寫的長度,不關閉流繼續下一次讀操作則接著上次的輸出繼續輸出;

           3 fprintf() : 按格式輸入到流,其原型是int fprintf(FILE *stream, const char *format[, argument, ...]);其用法和printf()相同,不過不是寫到控制台,而是寫到流罷了。注意的是傳回值為此次操作寫入到檔案的位元組數。如int c = fprintf(fp, "%s %s %d %f", str1,str2, a, b) ;str1:10位元組;str2: 10位元組;a:2位元組;b:8位元組,c為33,因為寫入時不同的資料間自動加入一個空格。

檔案使用之後一定要關閉,否則將不能正確顯示內容.fwrite:讀入兩個學生資訊然後用fwrite存入檔案

fread:用fread從檔案中讀出學生資訊。

fwrite.c

#include <stdio.h>
#define SIZE 2
struct student_type
{
 char name[10];
 int num;
 int age;
 char addr[10];
}stud[SIZE];
void save()
{
 FILE *fp;
 int i;
 if((fp=fopen("stu_list","wb"))==NULL)
 {
  printf("cant open the file");
  exit(0);
 }
 for(i=0;i<SIZE;i++)
 {
   if(fwrite(&stud[i],sizeof(struct student_type),1,fp)!=1)
    printf("file write error\n");
 }
 fclose(fp);
}
main()
{
 int i;
 for(i=0;i<SIZE;i++)
 {
   scanf("%s%d%d%s",&stud[i].name,&stud[i].num,&stud[i].age,&stud[i].addr);
   save();
 }
 for(i=0;i<SIZE;i++)
 {
   printf("%s,%d,%d",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
 }
}

fread.c

#include <stdio.h>
#define SIZE 2
struct student_type
{
 char name[10];
 int num;
 int age;
 char addr[10];
}stud[SIZE];
void read()
{
 FILE *fp;
 int i;
 if((fp=fopen("stu_list","rb"))==NULL)
 {
  printf("cant open the file");
  exit(0);
 }
 for(i=0;i<SIZE;i++)
 {
   if(fread(&stud[i],sizeof(struct student_type),1,fp)!=1)
    printf("file write error\n");
 }
 fclose(fp);
}
main()
{

 int i;
 read();
 for(i=0;i<SIZE;i++)
 {
   printf("%s,%d,%d,%s",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
   printf("\n");
 }
}

在C語言中進行檔案操作時,我們經常用到fread()和fwrite(),用它們來對檔案進行讀寫操作。下面詳細紹一下這兩個函數的用法。

  我們在用C語言編寫程式時,一般使用標準檔案系統,即緩衝檔案系統。系統在記憶體中為每個正在讀寫的檔案開闢“檔案緩衝區”,在對檔案進行讀寫時資料都經過緩衝區。要對檔案進行讀寫,系統首先開闢一塊記憶體區來儲存檔案資訊,儲存這些資訊用的是一個結構體,將這個結構體typedef為FILE類型。我們首先要定義一個指向這個結構體的指標,當程式開啟一個檔案時,我們獲得指向FILE結構的指標,通過這個指標,我們就可以對檔案進行操作。例如:

#i nclude <stdio.h>

#i nclude <string.h>

int main()

{

   FILE *fp;

   char buffer[100] = "This is a test";

   if((fp = fopen("c:\\example.txt", "w")) == 0)

    {

       printf("open failed!");

       exit(1);

    }

   fwrite(buffer, 1, strlen("This is a test"), fp);

   fclose(fp);

   return 0;

}

  通過以上代碼,我們就在c盤的根目錄下建立了一個名為example副檔名為.txt的檔案,我們開啟可以看到上面寫上了This is a test。當我們對它將它讀出時,用如下代碼:

#i nclude <stdio.h>

#i nclude <mem.h>

int main()

{

   FILE *fp;   int len;

   char buffer[100];

   /*memset(buffer, 1, 100); */

   if((fp = fopen("c:\\example.txt", "r")) == 0)

    {

       printf("open failed!");

       exit(1);

    }

   fseek(fp, 0L, SEEK_END);

   len = ftell(fp);

   rewind(fp);

   fread(buffer, 1, len , fp);

   printf("%s",buffer);

   fclose(fp);

   getch();

   return 0;

}

 可以看到,當我們使用memset了以後,讀出了一大堆亂碼,這是為什麼呢?原因是我們在fwrite函數時寫入的位元組數是用strlen求得的,也就是說字串最後的‘\0‘並沒有寫到檔案中去。所以我們從檔案中讀到buffer中時也自然沒有‘\0‘,因為buffer中的數是隨機的,除非buffer中最後一個字元的下一個數恰好隨機到0(可能性很小,這裡用memset將它排除),否則以%s將buffer中的字元輸出時遇不到0,所以亂碼產生。解決的辦法有很多,你可以在向檔案寫資料時多寫入一個位元組,系統會自動寫入0,fwrite(buffer, 1, strlen("This is a test")+1, fp);這樣讀出時最後就有一個0了。或者讀出操作完成後,在最後一個字元後面補上一個0:buffer[len] = 0;這樣問題也可得到解決。
 


本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/greytree/archive/2006/06/02/769952.aspx

【轉】fread函數和fwrite函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.