c語言將數據寫入文件
『壹』 c語言如何寫入文本文件
1、首先輸入下方的代碼
#include <stdio.h>
int main()
{
//下面是寫數據,將數字0~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語言編的程序的結果輸入到一個文本文件中
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語言中怎麼把一個結構體數組寫入文件
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語言中,如何把數組里的數據寫入文件
使用for循環語句+文件操作函數即可把數組里的數據寫入文件。
1、C語言標准庫提供了一系列文件操作函數。文件操作函數一般以f+單詞的形式來命名(f是file的簡寫),其聲明位於stdio.h頭文件當中。例如:fopen、fclose函數用於文件打開與關閉;fscanf、fgets函數用於文件讀取;fprintf、fputs函數用於文件寫入;ftell、fseek函數用於文件操作位置的獲取與設置。一般的C語言教程都有文件操作一章,可以找本教材進一步學習。2、常式:
#include<stdio.h>
int i,a[100];
int main(){
FILE * fp1 = fopen("input.txt", "r");//打開輸入文件
FILE * fp2 = fopen("output.txt", "w");//打開輸出文件
if (fp1==NULL || fp2==NULL) {//若打開文件失敗則退出
puts("不能打開文件!");
rturn 0;
}
for(i=0;fscanf(fp1,"%d",a+i)!=EOF;i++);//從輸入文件連續讀取整數到數組a
for(;i--;)fscanf(fp2,"%d ",a[i]);//把數組a逆序寫入到輸出文件當中
fclose(fp1);//關閉輸入文件
fclose(fp2);//關閉輸出文件,相當於保存
return 0;
}