C++将数组保存入.txt文件
C++中,将数组的内容写入.txt文件,下面介绍两种方法,以及各自的特点。
fwrite()
函数
可以一次性将数组的内容全部写入文档,但该方法是以二进制的方式写入的。
#include <stdio.h>
#include <stdlib.h>
int main ()
{
FILE * pFile;
int buffer[] = {1, 2, 3, 4};
if((pFile = fopen ("test.txt", "wb"))==NULL)
{
printf("cant open the file");
exit(0);
}
//可以写多个连续的数据(这里一次写4个)
fwrite (buffer , sizeof(int), 4, pFile);
fclose (pFile);
return 0;
}
我们测试一下,随便生成了64个整数,保存入.txt。用记事本打开:
再用代码编辑器(Sublime Text)打开:
可以看到,数组内容是以二进制的方式保存的,当我们使用文本文档打开时,看到的是乱码也就不足为奇了。
fprintf()
函数
将数组中的数字逐个写入文档。
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE * fp;
int data[5] = {1,2,3,4,5};
if((fp = fopen("text_2.txt","wb"))==NULL){
printf("cant open the file");
exit(0);
}
int i;
for(i=0;i<5;i++){
fprintf(fp,"%d ",data[i]);
}
fclose(fp);
return 0;
}
以上。?