C++ File I/O

文件I/O,此处仅处理由ASCII编码的文本,C++有两个处理文件的基本类,ifstream,ofstream,前者处理输入(从文件中读入内容),后者处理输出(写入文件);

在使用时需要在头文件中包含

#include <ifstream>
         // Library to specifically deal with input
         //of text files.  Does not deal with
         //output.

#include <ofstream>
         //Library to specifically deal with output
         //of text files.  Does not deal with
         //input.

#include <fstream>
         //Library to deal with BOTH input and output.

可以采取下述方式声明:

Ifstream a_file 

Or

Ifstream a_file( “filename”)

 以文件名为参数,调用默认的构造函数。两个类都有打开(a_file.open())和关闭(a_file.close())。

也可以不用调用a_file.close()。因为在程序结束时会自动调用。但如若需要在程序结束较前关闭文件,可以调用. 

强大的C++处理类,及操作符重载,可以调用<<和>>进行I/O.

一个例子:

#include <fstream>
#include <iostream>

using namespace std;

int main()
{
  char str[10];

  //Creates an instance of ofstream, and opens example.txt
  ofstream a_file ( "example.txt" );
  // Outputs to example.txt through a_file
  a_file<<"This text will now be inside of example.txt";
  // Close the file stream explicitly
  a_file.close();
  //Opens for reading the file
  ifstream b_file ( "example.txt" );
  //Reads one string from the file
  b_file>> str;
  //Should output 'this'
  cout<< str <<"\n";
  cin.get();    // wait for a keypress
  // b_file is closed implicitly here
}

默认时,打开一个ofstream文件,若不存在,则新建;若已经存在,则删除已有的内容。

可以通过参数设置,进行修改:

ios::app   -- Append to the file
ios::ate   -- Set the current position to the end
ios::trunc -- Delete everything in the file

例如:

ofstream a_file ( "test.txt", ios::app );

如此打开文件,将会在现有文件的结尾继续写入。

对于能否成功打开文件,需要进行验证,以保证安全性。

ifstream a_file ( "example.txt" );

if ( !a_file.is_open() ) {
  // The file could not be opened
}
else {
  // Safely use the file stream
}

从文件流中读入数据,有关于EOF的应用,例如:

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

int main () {
  string line;
  
  //the variable of type ifstream:
  ifstream myfile ("example.txt");
  
  //check to see if the file is opened:
  if (myfile.is_open())
  {
    //while there are still lines in the
    //file, keep reading:
    while (! myfile.eof() )
    {
      //place the line from myfile into the
      //line variable:
      getline (myfile,line);

      //display the line we gathered:
      cout << line << endl;
    }

    //close the stream:
    myfile.close();
  }

  else cout << "Unable to open file";

  return 0;
}
粗略写了一个小代码,用于统计输入文件的行数,空格数,单词数,及标点符号数目;未debug;
#include <fstream>
using namespace std;

typedef struct FILEINFO{
	int lines;
	int punction;
	int character;
	int blank;
}fileInfo;

int main(int argc, char** arg)
{
	//if (argc < 1)
	{
		cout<< "please check!" << endl;
	}
	string filename = string(arg[1]);
	ifstream curFileStream(filename,ios::in);
	char curChar;
	fileInfo* curFileInfo = new fileInfo[1];
	bool charFlat = false;
	if (curFileStream.is_open())
	{
		while (!curFileStream.eof() && curFileStream.get(curChar))
		{
			switch (curChar)
			{
			case '\n':
				curFileInfo->lines++;
				if (charFlat)
				{
					curFileInfo->character++;
					charFlat = false;
				}
				break;
			case ' ':
				curFileInfo->blank++;
				if (charFlat)
				{
					curFileInfo->character++;
					charFlat = false;
				}
				break;
			default:
				if (curChar<'z'&&curChar>'a')
					charFlat = true;
				break;
			}
			
		}
	}
	else
		exit(1);
	
	return 0;
}


参考原文


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
 一、ASCII 输出   为了使用下面的方法, 你必须包含头文件<fstream.h>(译者注:在标准C++中,已经使用<fstream>取 代< fstream.h>,所有的C++标准头文件都是无后缀的。)。这是 <iostream.h>的一个扩展集, 提供有缓 冲的文件输入输出操作. 事实上, <iostream.h> 已经被<fstream.h>包含了, 所以你不必包含所有这两个 文件, 如果你想显式包含他们,那随便你。我们从文件操作类的设计开始, 我会讲解如何进行ASCII I/O 操作。如果你猜是"fstream," 恭喜你答对了! 但这篇文章介绍的方法,我们分别使用"ifstream"?和 "ofstream" 来作输入输出。   如果你用过标准控制台流"cin"?和 "cout," 那现在的事情对你来说很简单。 我们现在开始讲输出部 分,首先声明一个类对象。 ofstream fout;   这就可以了,不过你要打开一个文件的话, 必须像这样调用ofstream::open()。 fout.open("output.txt");   你也可以把文件名作为构造参数来打开一个文件. ofstream fout("output.txt");   这是我们使用的方法, 因为这样创建和打开一个文件看起来更简单. 顺便说一句, 如果你要打开的文 件不存在,它会为你创建一个, 所以不用担心文件创建的问题. 现在就输出到文件,看起来和"cout"的操 作很像。 对不了解控制台输出"cout"的人, 这里有个例子。 int num = 150; char name[] = "John Doe"; fout << "Here is a number: " << num << " "; fout << "Now here is a string: " << name << " ";   现在保存文件,你必须关闭文件,或者回写文件缓冲. 文件关闭之后就不能再操作了, 所以只有在你 不再操作这个文件的时候才调用它,它会自动保存文件。 回写缓冲区会在保持文件打开的情况下保存文 件, 所以只要有必要就使用它。回写看起来像另一次输出, 然后调用方法关闭。像这样: fout << flush; fout.close();    现在你用文本编辑器打开文件,内容看起来是这样:   Here is a number: 150 Now here is a string: John Doe   很简单吧! 现在继续文件输入, 需要一点技巧, 所以先确认你已经明白了流操作,对 "<<" 和">>" 比较熟悉了, 因为你接下来还要用到他们。继续…   二、ASCII 输入   输入和"cin" 流很像. 和刚刚讨论的输出流很像, 但你要考虑几件事情。在我们开始复杂的内容之前 , 先看一个文本:   12 GameDev 15.45 L This is really awesome!   为了打开这个文件,你必须创建一个in-stream对象,?像这样。 ifstream fin("input.txt");   现在读入前四行. 你还记得怎么用"<<" 操作符往流里插入变量和符号吧?好,?在 "<<" (插入)?操作 符之后,是">>" (提取) 操作符. 使用方法是一样的. 看这个代码片段.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值