fileline.cpp

来自「c语言教程源码」· C++ 代码 · 共 67 行

CPP
67
字号
//这个程序在本书所带软盘中,文件名为FILELINE.CPP
//这个程序将对读入的文本文件加行号以及空行,并将处理后的文件
//按照用户指定的文件名存入软盘中。

#include <fstream.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void main(void)
{
	void process(ifstream&, ofstream&);

	char in_file_name[30];
	char out_file_name[30];

	ifstream in_file;			//定义一个用于输入处理的文件
	ofstream out_file;			//定义一个用于输出处理的文件

	cout << "请输入要加行号的程序文件名: ";
	gets(in_file_name);
	cout << "请输入要储存结果的文件名: ";
	gets(out_file_name);

	cout << "正在处理......" << endl;
	cout << "请稍等....." << endl;

	in_file.open(in_file_name, ios::in);
	if(! in_file)
	{
		cout << "打开输入文件错误。检查文件盘后再试..." << endl;
		exit(1);
	}
	out_file.open(out_file_name, ios::out);
	if(! out_file)
	{
		cout << "建立输出文件错误。检查盘后再试..." << endl;
		exit(1);
	}

	process(in_file, out_file);

	in_file.close();
	out_file.close();

	cout <<"加行号处理完毕!" << endl;
}

/************** 子程序 process() ********************/
void process(ifstream &infile, ofstream &outfile)
{
	int linenum = 1;
	char line[81];

	while (infile.peek() != EOF)
	{
		infile.getline(line, 81);

		if(strlen(line))			//如果不是空行
		{
			outfile << linenum << "  ";
			outfile << line << endl;
			outfile << endl;		//加一个空行
			linenum++;
		}
	}
}

⌨️ 快捷键说明

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