c、c++写数据到文件

本文介绍了使用C和C++进行文件操作的方法,包括文件的打开、读写及关闭等基本流程。通过示例展示了如何从键盘接收数据并将其写入文件的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//c
#include<stdio.h>
int main()
{
FILE* fp;
fp = fopen("a:xxxkl.dat","w");
fp = fopen("xxxkl.dat", "wb");
if (fp == NULL)
{
printf("打开失败\n");
return  -1;
}
int a;
scanf("%d", &a);
while (a != -1)
{
fputc(a, fp);
scanf("%d", &a);


}
fclose(fp);


return 0;
}








//c++

对于c++文件操作:头文件:#include<fstream>

输出流: ofstream fout(" 路径");    fout<<x;            fout.close();

输入流:ifstream fin(" 路径");    fin<<x;            fin.close();


#include<stdlib.h>
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream fout("xxxkl.dat");// 定义输出文件流并打开文件
if (!fout)
{
cout << "打开失败"<<endl;
return -1;


}
int a;
cin >> a;
while (a != -1)
{
fout << a << "  ";
cin >>a;
} // 能够从键盘向文件正确输出数据
fout.close();   // 关闭输出文件流
return 0;

}


文件操作函数
答:FILE *fp 
fopen(“filename”, “rwatb+”) 
char ch ch = fgetc(fp) fputc(ch, fp) 
char str[n] fgets(str, n, fp) fputs(str, fp) 
fread(buffer, size, count, fp) fwrite(buffer, size, count, fp) 
fscanf(fp, “%c”, &ch) fprintf(fp, “%d”, ch) 
fclose(fp) 
rewind(fp) 
fseek(fp, 偏移长度,SEEK_SET/SEEK_CUR/SEEK_END) 
feof(fp)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值