文档的读写


法一、
#include 
#include 
#include 
using namespace std;

int main()
{
	//读入文件
	ifstream in;
	string filename;
	getline(cin, filename, '\n');
	in.open(filename);
	if (!in){ cout << "文件读取失败" << endl; return 1; }
	
	char ch;
	while (!in.eof())
	{
		in.read(&ch, 1);
		cout << ch;
	}
	in.close();
}

法二、

    FILE* fp1 = fopen("in.txt", "r");//绝对路径双反斜杠
	FILE* fp2 = fopen("out.txt", "w");//freopen,fopen_s: 函数不接受 2 个参数
	if (!fp1 || !fp2)
	{
		cout << "open file error" << endl;
		return 1;
	}
	int a;
	char string[1024],b;
	fgets(string, 100, fp1);//从输入文件读取一行字符串
	fscanf(fp1, "%d", &a);//从输入文件读取一个整数
	b = fgetc(fp1);//从输入文件读取一个字符
	
	fputs(string, fp2);//向输出文件写入一行字符串
	fprintf(fp2, "%d", a);//向输出文件写入一个整数
	fputc(b, fp2);//向输出文件写入一个字符
	cout << string << b << a << endl;


	fclose(fp1);
	fclose(fp2);


拓展:按行读取后对行内的每个字符进行操作

ifstream in;
	string filename="in.txt";
	string line;//存放字符串数组
	int i;
	in.open(filename);
	if (!in){ cout << "文件读取失败" << endl; return 1; }
	while (getline(in, line))
	{
		cout << line[0] << endl;
		cout << line[2] << endl;
	}
	in.close();


解决vs里error c4996:'fopen'问题的方法,修改vs的一点设置:解决error C4996: 'fopen'问题


除此之外,如果不用fopen函数,还可以通过定义open()函数: 打开文件open()函数的使用方法详解


























发布了48 篇原创文章 · 获赞 21 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_33810513/article/details/53164925