開檔 : 使用stdio.h的fopen()函數,第一個參數為檔案名稱,第二個參數為開啟模式。

FILE * fopen ( const char * filename, const char * mode );

1       

寫檔 : 使用stdio.h的fwrite()函數將array或是struct的內容寫入檔案中,第一個參數為array或是struct的指標,從這一個位址開始寫入,第二個參數為每一個元素被寫入的大小,第三個參數為寫入元素數量,第四個為指向FILE檔案指標。

size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );

小試身手小範例01 - 字元寫檔

#include <stdio.h>

int main(){

FILE *pFile;
char buffer[]={ 'H','e','y' };

pFile = fopen( "write.txt","w" );
if( NULL == pFile ){
printf( "open failure" );
return 1;
}else{
fwrite(buffer,1,sizeof(buffer),pFile);
}

fclose(pFile);
return 0;
}


小試身手小範例02 - 浮點數寫檔

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){

int i = 0;
double *Tmp;
FILE *pFileBefore;
char cBuffer[8];

pFileBefore = fopen("Before.txt","wb");

Tmp = (double *)malloc(sizeof(double)* 10);
memset( Tmp, 0x00, sizeof(double)* 10);

if( NULL == pFileBefore)
{
printf(" failure");
return 1;
}

for( i=0; i<10; i++)
{
Tmp[i] = (double)(i);
printf( "%f\n", Tmp[i] );
sprintf( cBuffer, "%f ", Tmp[i]);
fwrite( cBuffer, 1, sizeof(double) + 1, pFileBefore );
}

fclose(pFileBefore);

return 0;

}

 

相關文章

[ C ] Read 讀檔

arrow
arrow

    S 發表在 痞客邦 留言(0) 人氣()