[英]File won't open for writing
我正在嘗試將數據結構的內容寫入文件,但是由於某種原因,file.is_open()返回false。 我想念什么嗎? 當我使用cout測試時,打印應該可以正常工作。
std::ofstream file;
file.open(filename, std::ofstream::out | std::ofstream::trunc);
for(int i = 0; i < 1000; ++i) {
Candy* tmp = index[i];
for(; tmp; tmp = tmp->next){
if(file.is_open()){
file << tmp->ID << ";" << tmp->amount << ";" << tmp->location <<
}
else{
std::cout << "error" << std::endl;
}
}
file.close();
}
您是否具有寫入文件路徑的正確權限? 文件路徑實際存在嗎?
您可以檢查errno來找出問題所在。
#include <cerrno>
std::cout << "File error: " << strerror( errno ) << std::endl;
可能是您的花括號不匹配? 您永遠不會超出第一個for循環的范圍,因此要在循環的第一次迭代中關閉文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.