繁体   English   中英

C ++ ifstream不会打开任何文件

[英]C++ ifstream will not open any files

每当我尝试使用ifstream打开文件时,它编译得很好,但不会打开文件。 此示例中的文件不存在,但ifstream * s *应* s *为我创建文件。

我有一些示例代码,我认为应该工作,但不打开或创建文件“foo.txt”。 有什么东西我不见了,或者我的IDE搞砸了? 我正在使用visual studio 2008 VC ++,顺便说一句

谢谢

这是代码:

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

using namespace std;

int main(){
    ifstream in;
    string hold;
    in.open("foo.txt",ios::in);
    if(!in){
        cerr << "Couldn't open file!" << endl;
    }
    in >> hold;
    cout << hold << endl;
    system("pause");
    return 0;
}

问题是你正在使用in stream而不是out stream,就像Adam Liss所提到的那样( ios::out而不是ios::in )。 您还需要确保在return 0;之前关闭文件return 0; 确保缓冲区中的所有内容都实际写入文件。

open函数不会在ios::in模式下创建文件; 你需要使用ios::out

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM