fstream进出不存在的文件 [英] fstream in and out on nonexistent file
问题描述
是否可以在ios :: in&都不存在的文件上打开fstream ios :: out而不会出现错误?
Is it possible to open an fstream on a file that does not exist with both ios::in & ios::out without getting an error?
推荐答案
要打开 fstream
在不存在输入和输出(随机访问)但没有出现错误的文件上,您应该提供 open
(或
To open an fstream
on a file that does not exist for input and output (random access) without getting an error, you should provide the flags fstream::in | fstream::out | fstream::trunc
in the open
(or constructor) call. Since the file does not already exist, truncating the file at zero bytes is no drama.
在打开仅指定 ios::in
时不存在的文件时,可能会出现错误,因为您将永远无法从流中读取内容,因此在这种情况下尽早失败将防止以后发生意外失败.
You may want an error when opening a file that doesn't exist when specifying only ios::in
since you'll never be able to read from the stream so failing early in this case will prevent surprise failures later on.
这篇关于fstream进出不存在的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!