C语言文件与数组之间输入输出操作

C语言文件与数组之间输入输出操作

文件存到数组里面:

#include<iostream>
#include<fstream>
#include<string>
#include<cstdio>
#include<cstdlib>
using namespace std;
int main()
{	
	fstream fs("test.txt");
	istreambuf_iterator<char> beg(fs),end;
	string data(beg,end);
	cout<<data<<endl;
	system("pause");
    return 0;
}

这个代码保存的位置下新建一个文件,名为test.txt。
在这里插入图片描述
然后文件中所有字符存到data字符串里面。

输出字符串,可看出各种字符都被读到data里面了。

在这里插入图片描述

数组存到文件里面:

#include<iostream>
#include<fstream>
#include<string>
#include<cstdio>
#include<cstdlib>
using namespace std;
int main()
{	
	fstream fs("test.txt");
	istreambuf_iterator<char> beg(fs),end;
	string data(beg,end);
	FILE * f;
    f= fopen("1.txt", "w");
	for(int i=0; data[i]; i++) fprintf(f, "%c", data[i]);
	fclose(f);
	system("pause");	
	return 0;
}

data存了test.txt里面的数据,现在我们把data输出到另一个文件1.txt。

在这里插入图片描述
在这里插入图片描述

自定义文件路径:

#include<iostream>
#include<fstream>
#include<string>
#include<cstdio>
#include<cstdlib>
using namespace std;
int main()
{	
	char* file1=(char*)malloc(sizeof(char)*100000);
	char* file2=(char*)malloc(sizeof(char)*100000);
	printf("请输入要打开的文件名(含路径):\n");
	gets(file1);
	fstream fs(file1);
	istreambuf_iterator<char> beg(fs),end;
	string data(beg,end);
	cout<<data<<endl;
	system("pause");
	
	FILE * f;
	printf("请输入要保存的文件名(含路径):\n");
	gets(file2);
	f = fopen(file2, "w");
	for(int i=0; data[i]; i++) fprintf(f, "%c", data[i]);
	fclose(f);
	system("pause");
	
	return 0;
}

输入一个地址作为数据文件,存到数组里。

再输入一个地址作为输出文件,数组所有字符输出到这个文件里。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

发布了218 篇原创文章 · 获赞 131 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/qq_40828914/article/details/90524651