c、c++写数据到文件

来源:互联网 发布:快看漫画mac 编辑:程序博客网 时间:2024/05/18 05:08
//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)

1 0
原创粉丝点击