C語言程式靜態庫和動態庫的建立及其應用

來源:互聯網
上載者:User

在用c寫程式時,很多時候需要儲存一些簡單的資料,如果為此而用mysql資料庫就有些大才小用了,可以把這些資料以結構的形寫入檔案,然後再需要時讀取檔案,取出資料。

如下是定義函數的源檔案和標頭檔:

源檔案struct.c:

#include "struct.h"
//第一個參數是要寫入的檔案名稱,第二個參數是緩衝區,第三個參數是緩衝區大小,
第四個參數是開啟檔案流的形態,返回TRUE表示寫入成功,返回FALSE表示寫入失敗
int writeStruct(const char *fileName,char *buffer,int bufferLen,char *mode){
   int ret;
   FILE *fileID = NULL;
   fileID = fopen(fileName,mode);
   if (fileID == NULL){
     perror("fopen");
     goto writeEnd;
   }
   rewind(fileID);
   ret = fwrite(buffer,bufferLen,1,fileID);
   if (ret <= 0){
     perror("fwrite");
     goto writeEnd;
   }
   if (fileID != NULL){
     fclose(fileID);
     fileID = NULL;
   }
   return TRUE;
writeEnd:
   if (fileID != NULL){
     fclose(fileID);
     fileID = NULL;
   }
   return FALSE;
}
//第一個參數是要讀取的檔案名稱,第二個參數是緩衝區,第三個參數是緩衝區大小,第四個參數是開啟檔案流的形態,返回TRUE表示讀取成功,返回FALSE表示讀取失敗
int readStruct(const char *fileName,char *buffer,int bufferLen,char *mode){
   int ret;
   FILE *fileID = NULL;
   fileID = fopen(fileName,mode);
   if (fileID == NULL){
     perror("fopen");
     goto readEnd;
   }
   rewind(fileID);
   memset(buffer,0,sizeof(buffer));
   ret = fread(buffer,bufferLen,1,fileID);
   if (ret >= 0){
     strcat(buffer,"\0");
   }else{
     perror("fread")  ;
     goto readEnd;
   }
   if (fileID != NULL){
     fclose(fileID);
     fileID = NULL;
   }
   return TRUE;
readEnd:
   if (fileID != NULL){
     fclose(fileID);
     fileID = NULL;
   }
   return FALSE;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.