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;
}