C++输入输出流(读取,写入,复制文件)
程序员文章站
2024-03-18 17:54:10
...
//读取文件内容
#include<string>
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char c;
fstream file;
file.open("test.txt",ios::in);
while (!file.fail())
{
if (file.get(c))
{
cout << c;
}
}
file.close();
}
//写入文件
#include<string>
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
cout << "Creat a file" << endl;
ofstream file;
file.open("test.txt",fstream::app);
if (!file.fail())
{
file << "你好" << endl;
file << "还好" << endl;
file.close();
}
}
}
//C++实现文件复制
#include<string>
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char c;
int sum=0;
fstream infile,outfile;
infile.open("test.txt",ios::in); //打开目标文件
outfile.open("Demo.txt",ios::out); //创建文件别名(复制)
if (!infile.fail()) //检查文件打开是否成功
{
cout << "开始写入文件........" << endl;
while (infile.get(c)) //从打开的文件中写入字符
{
outfile << c;
sum++;
}
}
cout << "总计输入字符:" <<sum<< endl;
infile.close();
outfile.close();
cout << "文件写入复制完毕........" << endl;
}
}
上一篇: 浮点型在内存中的存储