C++用ofstream创建的文件,无法打开的情形

代码里有else{//Couldn'topenthefile.std::cout<<"Thefilecouldnotbeopened!\n";return1;//Indi... 代码里有
else { // Couldn't open the file.
std::cout << "The file could not be opened!\n";
return 1; // Indicates a problem occurred.
}
我想知道什么时候会发生这种情况,书上建议输入一个非法的文件路径试试看,要怎么做啊?

// quote2.cpp - Script 4.8

// We need the iostream file in order
// to use cout and cin.
#include <iostream>

// We need the string file
// for the string functionality.
#include <string>

// We need the fstream file in order
// to work with files.
#include <fstream>

// Start the main function.
int main() {

// Declare the necessary variables.
std::string quote, speaker;

// Prompt the user for the quotation.
std::cout << "Enter a quotation (without quotation marks):\n";
std::getline(std::cin, quote);

// No extraneous input to be discarded
// because all input is assigned to the string!

// Prompt the user for the quotation's author.
std::cout << "Enter the person to whom this quote is attributed:\n";
std::getline(std::cin, speaker);

// Create a blank line in the output.
std::cout << "\n";

// Repeat the input back to the user.
std::cout << "The following quote has been received...\n\n"
<< quote << "\n-" << speaker << "\n\n";

// Write the data to the file.

// Define a file object.
std::ofstream fileOutput("quotes.pdf", std::ios::app);

// If the file is open, record the data.
if (fileOutput.is_open()) {

// Write the data to the file.
fileOutput << quote << "|"
<< speaker << "\n";

// Close the stream.
fileOutput.close();

// Print a message.
std::cout << "The data has been written to the file!\n";

} else { // Couldn't open the file.
std::cout << "The file could not be opened!\n";
return 1; // Indicates a problem occurred.
}

// Wait for the user to press Enter or Return.
std::cout << "Press Enter or Return to continue.\n";
std::cin.get();

// Return the value 0 to indicate no problems.
return 0;

} // End of the main() function.
展开
 我来答
doudou745
2011-10-23 · TA获得超过233个赞
知道小有建树答主
回答量:132
采纳率:0%
帮助的人:144万
展开全部
楼主,我试了下,在我电脑上是可以正常运行的。你重新新建个工程试试。。。
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
powerstone_83
2011-10-23 · TA获得超过2265个赞
知道小有建树答主
回答量:564
采纳率:100%
帮助的人:303万
展开全部
是不是可以尝试在不存在的目录里打开一个文件,或者在你没有权限的目录下打开一个文件?
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 2条折叠回答
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式