2009-04-28 57 views
7

我一直在這裏關於ifstream的問題,所以我仍然無法閱讀簡單的文本文件。我與Visual Studio 2008年的工作ifstream :: open在Visual Studio調試模式下不工作

這裏是我的代碼:

// CPPFileIO.cpp : Defines the entry point for the console application. 
// 

#include "stdafx.h" 
#include <fstream> 
#include <conio.h> 
#include <iostream> 
#include <string> 

using namespace std; 


int _tmain(int argc, _TCHAR* argv[]) 
{ 

    ifstream infile; 
    infile.open("input.txt", ifstream::in); 

    if (infile.is_open()) 
    { 
     while (infile.good()) 
      cout << (char) infile.get(); 
    } 
    else 
    { 
     cout << "Unable to open file."; 
    } 
    infile.close(); 
    _getch(); 
    return 0; 
} 

我已經證實,input.txt中文件是正確的「工作目錄」通過檢查argv[0]值。 Open方法不起作用。

我也遇到了調試問題 - 我不能在infile.good()infile.is_open()上設置手錶嗎?我不斷收到

Error: member function not present. 

編輯:從.cpp文件中完整的代碼更新的代碼清單。

更新:該文件不在當前工作目錄中。這是項目文件所在的目錄。將它移到那裏,它在VS.NET中調試時工作。

+0

其工作目錄是你的問題。當你從命令行運行它時,工作目錄是顯而易見的。當你在調試器中運行它時,你需要明確地設置工作目錄,否則它不是那麼明顯(檢查調試器選項)。 – 2009-04-29 00:41:49

+0

感謝您發佈更新部分。自從我需要考慮工作目錄處於調試模式的位置以來,這已經過去了一分鐘。爲我節省了幾分鐘的頭部劃傷。 – 2014-06-25 01:55:38

回答

8

嘗試在指定打開模式時使用按位或運算符。

infile.open ("input.txt", ios::ate | ios::in); 

openmode參數是一個位掩碼。 ios::ate用於打開要附加的文件,而ios::in用於打開文件以進行讀取輸入。

如果你只是想讀取文件,你可能只需要使用:

infile.open ("input.txt", ios::in); 

的默認打開方式爲ifstream的是IOS ::中,這樣你就可以得到完全擺脫這種現在。以下代碼適用於使用g ++的我。

#include <iostream> 
#include <fstream> 
#include <cstdio> 

using namespace std; 

int main(int argc, char** argv) { 
    ifstream infile; 
    infile.open ("input.txt"); 

    if (infile) 
    { 
     while (infile.good()) 
      cout << (char) infile.get(); 
    } 
    else 
    { 
     cout << "Unable to open file."; 
    } 
    infile.close(); 
    getchar(); 
    return 0; 
} 
+0

heh。有時候我希望我的代表能夠接受別人的答案。 :-) – 2009-04-28 17:11:40

0
infile.open ("input.txt", ios::ate || ios::in); 

||是邏輯或操作,而不是位運算符(如比爾的Lizzard所述)。

,所以我猜你正在做的等價於:

infile.open ("input.txt", true); 

(假設既不是iOS ::吃或iOS ::在0)

0

嘗試使用:

ifstream fStm("input.txt", ios::ate | ios::in); 

I'm also having trouble debugging- should I not be able to set a watch on "infile.good()" or "infile.is_open()"? I keep getting "Error: member function not present."

和適當包括:

#include <fstream> 

1

我發現代碼中的兩個問題:

一)語法錯誤 「的ios ::吃|| IOS ::在」=>應該是 「IOS ::吃| IOS ::在」

二)「的ios ::吃」光標設置爲文件的結尾 - 所以你什麼也得不到,當你開始閱讀

所以只要去掉「::吃IOS」和你的罰款:)

的Ciao, 克里斯

4

有時,Visual Studio會將您的exe文件遠離您的源代碼。默認情況下,VS只能從你的exe文件開始查找文件。這個過程是從源代碼獲取來自同一目錄的輸入txt文件的簡單步驟。如果你不想修復你的IDE設置。

using namespace std; 

ifstream infile; 

string path = __FILE__; //gets source code path, include file name 
path = path.substr(0,1+path.find_last_of('\\')); //removes file name 
path+= "input.txt"; //adds input file to path 

infile.open(path); 

希望這可以幫助其他人快速解決問題。我花了一段時間才找到這個設置。

相關問題