導航:首頁 > 文件教程 > 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寫入文件相關的資料

熱點內容
如何對excel文件加密不得修改 瀏覽:321
word編輯宏選中一段 瀏覽:458
微信怎麼上傳其他文件 瀏覽:220
互聯網數據分析需要哪些指標 瀏覽:844
eps包含鏈接文件 瀏覽:167
怎麼編程一些風景視頻 瀏覽:430
蘋果手機才能領的紅包嗎 瀏覽:823
js操作符 瀏覽:516
怎樣打開db文件里的圖片 瀏覽:820
卡仕達配置文件 瀏覽:419
怎樣恢復直接刪除的文件 瀏覽:587
pg資料庫怎麼遷移庫 瀏覽:610
什麼軟體存放文件不能下載的 瀏覽:888
jsp的書籍推薦 瀏覽:330
大數據處理培訓有哪些 瀏覽:163
蘋果二手機檢測多少錢 瀏覽:482
qq生日許願保存到哪了 瀏覽:658
鬥地主發牌程序c語言 瀏覽:996
cad安裝上為什麼文件夾是空的 瀏覽:676
mp3文件多少位元組 瀏覽:261

友情鏈接