⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ep9_7.cpp

📁 这里有大量的c语言习题呢!真的是题海哦
💻 CPP
字号:
/*9.7	以文本方式把一个文本文件(如C++源文件)的前十行拷贝到一个新的文件中。*/
#include<fstream>
#include<iostream>       //<fstream.h>不包含<iostream.h>
#include<cstdlib>
using namespace std;
int main(){
	int line=0;
	char filename[256],buf[256];
	fstream sfile,dfile;
	cout<<"输入源文件路径名:"<<endl;//请用s.txt,如用s.doc(word文档)则失败
	cin>>filename;//对路径各方面而言空格是无关紧要的,否则要用getline()等成员函数
	sfile.open(filename,ios::in);//打开一个已存在的文件
	while(!sfile){
		cout<<"源文件找不到,请重新输入路径名:"<<endl;
		sfile.clear(0);//出错后,状态必须清0
		cin>>filename;
		sfile.open(filename,ios::in);
	}
	cout<<"输入目标文件路径名:"<<endl;//请用d.txt
	cin>>filename; //只能创建文件,不能建立子目录,如路径不存在则失败
	dfile.open(filename,ios::out);
	if(!dfile){
		cout<<"目标文件创建失败"<<endl;
		return 1;
	}
	while(sfile.getline(buf,256),sfile.eof()!=1&&line<10){//按行拷贝  A行
		if(sfile.rdstate()==0) {
			dfile<<buf<<'\n';//因流正常,读到回车符,但未提取  B行
			line++;
		}
		else{
			dfile<<buf;//流不正常,还未读到回车换行符,所以不加'\n'
			sfile.clear();//状态字被置为0x02,必须清0
		}
	} 
	sfile.close();
	dfile.close();
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -