C++ File I/O

本文介绍了C++中处理文件输入输出的基本方法,包括ifstream和ofstream类的使用,以及如何打开、读取和关闭文件。此外,还展示了如何通过设置打开模式来控制文件的读写行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件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;
}


参考原文


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值