2010-10-17 207 views
0

這真的很奇怪。對於ifstream和ostream,絕對路徑不起作用。它適用於當我使用這樣的相對路徑:fstream絕對路徑不起作用

ofstream out; 
out.open("file2.txt"); 
string river = "i love cheese"; 

if(!out){ 
    cout << "error"; // have breakpoint set here 
} else { 
    out << river; // have breakpoint set here (stops here when debugging) 
} 

out.close(); 

但是,當我使用絕對路徑,它不。我很清楚需要使用「\」作爲斜槓,而我嘗試使用「/」來代替,而且它仍然不起作用。

ofstream out; 
out.open("C:\\file2.txt"); // also tried "C:/file2.txt" 
string river = "i love cheese"; 


if(!out){ 
    cout << "error"; // have breakpoint set here (stops here when debugging) 
} else { 
    out << river; // have breakpoint set here 
} 

out.close(); 

我真的需要它絕對路徑的工作,因爲這是提供的功能和輸入和輸出文件不會始終在同一文件夾中的二進制文件。

+0

您是否有權限在'C:'中編寫? – GManNickG 2010-10-17 19:37:13

+0

調用'perror(「open failed」);''out.open'評估爲false。這會告訴你它不起作用的原因。 – 2010-10-17 19:40:02

+0

Perror是否將錯誤輸出到控制檯?我正在製作一個沒有控制檯的Windows應用程序。 : -/ – alex 2010-10-17 19:42:29

回答

3

什麼是操作系統? Windows 7確實允許在C:\上創建文件而不是。您可以在C:\上創建新文件夾,例如C:\ temp \並嘗試下面的代碼:

std::ofstream out; 
out.open("C:\\temp\\asd.txt"); 
if(! out) 
{ 
    std::cout << "1"; 
} 
if (!out.is_open()) 
{ 
    std::cout << "2"; 
} 
out.close(); 

這工作正常。但是,當您嘗試在C:\上創建文件時,它將打印「12」。

+0

我使用Vista,但我只是使用「C:\」作爲簡化示例。我正在尋找輸入/輸出的文檔深入到「我的文檔」(這將有一個冗長的路徑用雙引號包圍)。 – alex 2010-10-17 20:24:06

+0

我想Vista和Windows 7一樣,因爲我們正在談論這些特權。嘗試其他目錄,它應該工作。只要你想,可以試試「我的文檔」。 – 2010-10-17 20:26:14

+0

這是可執行文件所在的文件夾,它仍然不會寫入: \「C:\\ Users \\ Alex \\ Documents \\ Visual Studio 2008 \\ Projects \\ outputProject \\ Debug \\ file2。 txt \「 – alex 2010-10-17 20:28:50