第十四周 项目一 小玩文件

<span style="font-size:18px;">【项目1 – 小玩文件】(1)下面程序的功能是统计文本文件abc.txt中的字符个数,</span><span style="font-size:18px;">#include <iostream>#include <cstdlib>#include <fstream>////fstream提供了三个类,用来实现c++对文件的操作。(文件的创建,读写)。// ifstream– 从已有的文件读//// ofstream– 向文件写内容//// fstream- 打开文件供读写////支持的文件类型////实际上,文件类型可以分为两种: 文本文件和二进制文件.using namespace std;int main(){fstream file;file.open("abc.txt", ios::in); // (2)读入文件(在此之前已经创建abc文本文件)if(!file) {cout<<"abc.txt can’t open."<<endl;exit(1);}char ch;int i=0;while(!file.eof()) // (3){file.get(ch);++i; // (4)}cout<<"Character: "<<i<<endl;file.close();// (5)读取完后关闭文件return 0;}</span>

(2)下面程序的功能是将文本文件abc.txt中的所有行加上行号后写到newabc.txt文件中,

<span style="font-size:18px;">/**Copyright (c)2014,烟台大学计算机与控制工程学院*All rights reserved.*文件名称:d.cpp*作 者:张旺华*完成日期:2015年6月14日*版 本 号:v1.0*/#include <iostream>#include <cstdlib>#include <fstream>using namespace std;int main(){fstream outfile,infile;infile.open("abc.txt",ios::in); // (1)if(!infile) {cout<<"Can’t open the file."<<endl;abort();}outfile.open("newabc.txt",ios::out);//(2)if(!outfile) {cout<<"Can’t open the file."<<endl;abort();}char buf[80];int i=1;while(!infile.eof()) // (3)判断是否读取结束{infile.getline(buf,80); // (4)outfile<<i++<<": "<<buf<<endl; //(5)}infile.close();outfile.close();return 0;}</span>

显然,当初的这个程序并未考虑超长行,而是默认每一行都不会达80个字符而设计的。注意:如果某一行就这样被“截断”了,,并不意味着这就是一行,直到找到换行符,才能说明这是一行的结束,行数i++才能执行,这个程序的改进又可以进行了。

可偏偏。多么温柔,一出口便是相互指责和嘲讽。

第十四周 项目一 小玩文件

相关文章:

你感兴趣的文章:

标签云: