導航:首頁 > 文件教程 > c寫入文件

c寫入文件

發布時間:2023-06-18 17:57:55

⑴ c語言中怎麼把一個結構體數組寫入文件

C語言把一個結構體數組寫入文件分三步:

1、以二進制寫方式(wb)打開文件

2、調用寫入函數fwrite()將結構體數據寫入文件

3、關閉文件指針

相應的,讀文件也要與之匹配:

1、以二進制讀方式(rb)打開文件

2、調用讀文件函數fread()讀取文件中的數據到結構體變數

3、關閉文件指針

參考代碼如下:

#include<stdio.h>
structstu{
charname[30];
intage;
doublescore;
};
intread_file();
intwrite_file();
intmain()
{
if(write_file()<0)//將結構體數據寫入文件
return-1;
read_file();//讀文件,並顯示數據
return0;
}

intwrite_file()
{
FILE*fp=NULL;
structstustudent={"zhangsan",18,99.5};
fp=fopen("stu.dat","wb");//b表示以二進制方式打開文件
if(fp==NULL)//打開文件失敗,返回錯誤信息
{
printf("openfileforwriteerror ");
return-1;
}
fwrite(&student,sizeof(structstu),1,fp);//向文件中寫入數據
fclose(fp);//關閉文件
return0;
}

intread_file()
{
FILE*fp=NULL;
structstustudent;
fp=fopen("stu.dat","rb");//b表示以二進制方式打開文件
if(fp==NULL)//打開文件失敗,返回錯誤信息
{
printf("openfileforreaderror ");
return-1;
}
fread(&student,sizeof(structstu),1,fp);//讀文件中數據到結構體
printf("name="%s"age=%dscore=%.2lf ",student.name,student.age,student.score);//顯示結構體中的數據
fclose(fp);//關閉文件
return0;
}

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

(1)buffer:指向結構體的指針(數據首地址)
(2)size:一個數據項的大小(一般為結構體大小)
(3)count: 要寫入的數據項的個數,即size的個數
(4)stream:文件指針。

⑵ 怎麼把c語言編的程序的結果輸入到一個文本文件中

c語租如旦言編橡局的程序的結果輸入到一個文本文件中可以使用fprintf;

例:

#include<stdio.h>

main(){

FILE *fpt;

fpt = fopen("wendangming.txt","w");//打開文檔弊擾,寫入

fprintf(fpt,"Hello world");

fclose(fpt);

}

(2)c寫入文件擴展閱讀

它打開一個文本文件,逐個字元地讀取該文件

#include <iostream>

#include <fstream>

using namespace std;

int main()

{

fstream testByCharFile;

int num;

char c;

testByCharFile.open("6.5.cpp",ios::in);

while(!testByCharFile.eof())

{

testByCharFile >> c;

num++;

}

testByCharFile.close();

cout << num << endl;

}

⑶ c語言寫入文件方法

對於學號來說int 或是char的影響不是很大,沒關系
至於讀取數據方面我同意二樓的解釋

⑷ C語言如何寫入文本文件

1、首先輸入下方的代碼

#include <stdio.h>

int main()

{

//下面是寫數據,將數字~9寫入到data.txt文件中

FILE *fpWrite=fopen("data.txt","w");

if(fpWrite==NULL)

{

return 0;

}

for(int i=0;i<10;i++)

fprintf(fpWrite,"%d ",i);

fclose(fpWrite);

//下面是讀數據,將讀到的數據存到數組a[10]中,並且列印到控制台上

int a[10]={0};

FILE *fpRead=fopen("data.txt","r");

if(fpRead==NULL)

{

return 0;

}

for(int i=0;i<10;i++)

{

fscanf(fpRead,"%d ",&a[i]);

printf("%d ",a[i]);

}

getchar();//等待

return 1;

}

⑸ c語言怎麼將數據寫入文件

利用VC軟體通過代碼書寫就可以將數據寫入文件。

閱讀全文

與c寫入文件相關的資料

熱點內容
linux下獲取目錄下所有文件名 瀏覽:422
note5怎麼退出應用程序 瀏覽:71
qq個性群網名 瀏覽:224
激盪三十年版本哪個好 瀏覽:950
移動內網怎麼傳文件夾 瀏覽:581
extjslicense 瀏覽:338
文件夾變成ink 瀏覽:124
七彩虹h110裝機教程 瀏覽:351
word三個減號回車 瀏覽:844
生存之旅22041升級補丁 瀏覽:825
強行進入別人微信空間 瀏覽:208
win81有線未識別網路 瀏覽:616
a7m3圖片配置文件視頻 瀏覽:471
linux設備驅動程序開發步驟 瀏覽:640
蘋果手機如何集中app 瀏覽:357
搜書王在哪個app下載 瀏覽:561
微程序控制單元的設計步驟 瀏覽:898
我的文件你放哪裡了 瀏覽:629
word備份文件位置 瀏覽:488
易我數據恢復怎麼操作 瀏覽:417

友情鏈接