作者xxxx5801 ()
看板C_and_CPP
標題[問題] fstream檔案莫名開啟失敗
時間Sat Aug 1 15:56:17 2015
最近在VS2012上作C++檔案讀取的練習, 語法方面沒有問題
但就是預期的結果跑不出來, 以下是程式碼:
#include"stdafx.h"
#include<iostream>
#include<fstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char chtem;
fstream io("d:\\123.txt", ios::in | ios::out);
if (!io){
cout << "File open failed!\n";
}
else{
cout << "File open successfully!\n";
while (io.get(chtem)){
cout << chtem;
}
}
io.close();
system("pause");
return 0;
}
輸出結果: File open failed!
作為測試的123.txt裡面就只有幾個英文字母而已
IDE也沒有任何錯誤訊息, 但io的值始終等於0
明明之前用C的fopen函數都OK, 但用C++來寫就有問題
有人跟我遇到同樣的問題嗎?
--
◤ ▁▁ ▁▁ ▁▁ ▂▄▆▆▆▅▃
█▄▄▄█ ╱ ╲ ▉ ▃ ◥ ▅ ▅ ■ ▃ ◢▃▃ ▃▃ ◣
▂█.︶. ╱▇ ╱ ╱ ▄ ◥ ◥▄ ╲ ▄ ▲██▊_▂_██▊ ▲
◢██▆▆▆▌ ▃▃▃ ▃▃☆▃ ▃ ▃▃▃ ▲ ◥◤◤ ▅ ◥◤◢ ◣
▉◥ ▄▄▄▄▄╭█╮▄◥▼◤▄▄▄▄▄ ●◢ ║ {︶} ║ ◣ ●
◥▉ ▎ ☆▂▁ ▂▲▲▁ ▃▃▄ ▄▄▄ ︶ ︶ vcfsvjf
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 39.9.1.194
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1438415784.A.235.html
推 s25g5d4: 你需要 ios::trunc 08/01 19:48
推 andy410061: 樓上那樣不是會把檔案清空嗎 08/02 11:38
感謝回答 ios::trunc 我有試過一樣不行
最後才發現是我把檔名打錯了 打成 123.txt.txt 難怪讀不到
※ 編輯: xxxx5801 (39.9.1.194), 08/02/2015 15:40:14
→ scott260202: ............... 08/02 16:59
推 Killercat: 這算fstream的致命問題,你其實很難搞懂為什麼失敗 XD 08/02 17:51
→ Killercat: 有興趣的話順手查察strerror(errno)怎麼運作的 08/02 17:51
→ Killercat: 他在fstream失敗的時候一樣會記錄下錯誤原因 08/02 17:52
→ Killercat: 這遠比單純看io是不是nulptr來的好得多 08/02 17:52
推 s25g5d4: 我沒有仔細看內文 以為是要建立新檔案 Orz 08/04 13:21
推 louisman: ......... 08/09 04:06