---
title: "ifstream 没有 ios::nocreate 属性"
author: "zengsai"
date: "2009-05-29T07:28:00Z"
tags: ["iOS"]
slug: "ifstream-ios-nocreate"
draft: false
lastmod: "2009-05-29T07:28:00Z"
id: 416731
url: "https://zengsai.iteye.com/blog/416731"
---

&lt;script&gt;function StorePage(){d=document;t=d.selection?(d.selection.type!='None'?d.selection.createRange().text:''):(d.getSelection?d.getSelection():'');void(keyit=window.open('http://www.365key.com/storeit.aspx?t='+escape(d.title)+'&u='+escape(d.location.href)+'&c='+escape(t),'keyit','scrollbars=no,width=475,height=575,left=75,top=20,status=no,resizable=yes'));keyit.focus();}&lt;/script&gt;

今天在 vs2008 中运行一个小程序的时候，发现了一个小问题，ifstream 的 open 函数中不能用 ios::nocreate 属性。详细见代码：

```
#include <fstream>
#include <iostream>
#include <stdlib><span style="color: #0000ff">int</span> main()
{
	<span style="color: #0000ff">using</span> <span style="color: #0000ff">namespace</span> std;
	
	ifstream inFile;

	inFile.open("<span style="color: #8b0000">my.dat</span>",ios::in | ios::nocreate);
	<span style="color: #0000ff">if</span>(!inFile)
	{
		cerr 不能打开my.dat" return 0;

}</stdlib></iostream></fstream>
```

出现错误:

```
error C2065: “nocreate”: 未声明的标识符
error C2065: “inFile”: 未声明的标识符
```

原因：从 vs 2003 开始，微软用一个新的 iostream 替换了原来的。新包中没有 nocreate 标识符。

原来 ifstream 中的 open 函数默认打开就是不创建文件。如果没有这个文件则打开出错，而不是创建文件。详见代码运行结果：

```
#include <fstream>
#include <iostream>
#include <stdlib><span style="color: #0000ff">int</span> main()
{
	<span style="color: #0000ff">using</span> <span style="color: #0000ff">namespace</span> std;

	ifstream inFile;

	inFile.open("<span style="color: #8b0000">my.dat</span>",ios::in);
	<span style="color: #0000ff">if</span>(!inFile)
	{
		cerr 不能打开my.dat" return 0;

}</stdlib></iostream></fstream>
```

运行结果：

[![未命名](http://p.blog.csdn.net/images/p_blog_csdn_net/zengsai/549028/o_%E6%9C%AA%E5%91%BD%E5%90%8D_thumb.jpg "未命名")](http://p.blog.csdn.net/images/p_blog_csdn_net/zengsai/549028/o_%E6%9C%AA%E5%91%BD%E5%90%8D_2.jpg)