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

熱點內容
cad能看word文件嗎 瀏覽:719
12306火車票系統後台資料庫 瀏覽:570
js翻譯德語 瀏覽:33
從哪裡可以下載a股的數據 瀏覽:437
邏輯文件名和物理文件名關系 瀏覽:66
怎麼查一個網站的外鏈 瀏覽:675
linux下db2安裝時版本選擇 瀏覽:738
匯編編程用哪個軟體 瀏覽:486
仙樂下的歌在文件管理哪裡 瀏覽:477
115網盤解析工具2014 瀏覽:371
內圓弧銑刀怎麼編程 瀏覽:410
記事本文件轉word格式對齊 瀏覽:300
excel刪除恢復文件 瀏覽:290
三星s4怎麼切換3g網路 瀏覽:994
什麼是網站維護 瀏覽:314
文件夾錄像在哪裡 瀏覽:621
可以發語音的是什麼app 瀏覽:804
恢復手機桌面文件管理 瀏覽:627
用什麼軟體可以打開psd文件 瀏覽:459
公安有哪些警務app 瀏覽:150

友情鏈接