C++文件输入输出

这篇博客详细介绍了C++中如何进行文件输入输出操作,包括从键盘读取整数到磁盘、从磁盘读取整数并输出、读取字符并转换大小写,以及二进制数据的存取。同时,博主提到了在Visual Studio中可能出现的乱码问题,并建议使用其他IDE以避免此类问题。

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

ASIIC文件的操作:
从键盘读取10个整数 到磁盘f1.dat,再从磁盘f1.dat读取10个整数并输出

// ConsoleApplication11.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include<fstream>
#include <iostream>
#include<algorithm>
using namespace std;
int in[10], out[10];
//从键盘输入10个整数,然后存放到磁盘中
void input(char *filename)
{
   
	ofstream outfile("f1.dat", ios::out);
	if (!outfile)
	{
   
		cerr << "打开错误!" << endl;
		exit(1);
	}
	cout << "读入10个整数到磁盘文件:" << endl;
	for (int i = 0; i < 10; i++)
	{
   
		cin >> in[i];
		outfile << in[i] << " " << endl;
	}
	outfile.close();
}
//从磁盘读取文件并输出
void output(char *filename)
{
   
	ifstream infile("f1.dat", ios::in);
	if (!infile)
	{
   
		cerr << "打开错误" << endl;
		exit(1);
	}
	cout << "磁盘文件读取10个整数:" << endl;
	for (int i = 0; i < 10; i++)
	{
   
		infile >> out[i];
		cout << out[i] << " ";
	}
	cout << endl;
	infile.close();
}
int main()
{
   
	char a[20] = "f1.dat";
	input(a);
	output(a);
	return 0;
}


从键盘读取一行字符,把其中的字母字符依次存放在磁盘文件f2.dat中,再把它从磁盘文件读入程序,将其中的小写字母依次改为大写字母,再存入f3.dat中。

#include<fstream>
#include <iostream>
#include<algorithm>
#include<string>
using namespace std;

//读入一行字符并将其中的字母存入磁盘文件
void save(char *filename)
{
   
	char s[80];
	ofstream outfile(filename, ios::out);
	if (!outfile)
	{
   
		cerr << "打开错误!" << endl;
		exit(1);
	}
	cout << "输入字符串保存到磁盘f2.dat" << endl;
	cin.getline(s, 80);
	for (int i = 0; i < strlen(s); i++)
	{
   
		if (s[i] >= 'a'&&s[i] <= 'z' || s[i] >= 'A'&&s[i] <= 'Z')
			outfile << s[i];
		cout << s[i];
	}
	cout << endl;
	outfile.close();
}
//从磁盘f2.dat读取字符串到程序,将其中的大写改为小写再存入f3.dat中
void get(char *filename1,char *filename2)
{
   
	char s;
	ifstream infile(filename1, ios::in);
	if (!infile)
	{
   
		cerr << "打开f2.dat错误!" << endl;
		exit(1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值