File Names in C++

C++ Primer 4/e在File Input and Output這個地方有一個警告:『For historical reasons, the IO library uses C-style character strings (Section 4.3, p. 130) rather than C++ strings to refer to file names. When we call open or use a file name as the initializer when creating an fstream object, the argument we pass is a C-style string, not a library string. Often our programs obtain file names by reading the standard input. As usual, it is a good idea to read into a string, not a C-style character array. Assuming that the name of the file we wish to use is in a string, we can use the c_str member (Section 4.3.2, p. 139) to obtain a C-style string.』

中文版的這樣寫:『由於歷史因素,IO程式庫使用C-style字元字串(4.3節.p.130)表示檔案名稱,而非使用C++ strings。當我們呼叫open()或在建立fstream物件時以檔名為初值,傳遞時的引數都必須是C-style字串而不是程式庫定義的strings。應用程式經常需要從標準輸入裝置取得檔名,把它讀入string是個好主意,不要讀入C-style字元array:假設我們想使用的檔名內含於某個string,可運用string提供的c_str()(4.3.2節,p.139)獲得C-style字串。』

對喔!之前一直讀到C-style的字串的問題,現在在file IO看到有差異的地方了,看來規定還是相沿已久來的傳統,不得不簽救救習慣啊!

感謝你看到這裡,很快就可以離開了,但最好的獎勵行動就是按一下幫我分享或留言,感恩喔~

點我分享到Facebook

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *