2014-04-24 9 views
6

의 차이 무엇입니까 :C++ - fstream 및 ofstream

fstream texfile; 
textfile.open("Test.txt"); 

ofstream textfile; 
textfile.open("Test.txt"); 

는 그 기능이 동일합니까?

답변

5

ofstream에는 출력 방법 만 있으므로 textfile >> whatever을 시도하면 컴파일되지 않습니다. fstream은 입력 및 출력에 사용할 수 있지만 작동하는 것은 생성자/open에 전달하는 플래그에 따라 다릅니다.

std::string s; 
std::ofstream ostream("file"); 
std::fstream stream("file", stream.out); 

ostream >> s; // compiler error 
stream >> s; // no compiler error, but operation will fail. 

덧글에 몇 가지 중요한 점이 더 있습니다.

+1

또한,'ofstream :: open'의 기본값은 openmode'ios_base :: out'이며,'fstream :: open'의 기본값은'ios_base :: in | ios_base :: out' –

+5

또한'std :: fstream'의 경우, 파일이 존재하지 않으면 파일을 열려고하면 실패합니다. 이는 찾을 수없는 파일을 만드는'std :: ofstream'과는 대조적입니다. 하나는'std :: ios_base :: trunc' 플래그를 마스크에 추가하거나 생성자를 호출 할 때'std :: fstream'에'open()'을 써야합니다. – 0x499602D2

0

해당 페이지를 cplusplus.com herehere에서 살펴보십시오.

ofstreamostream에서 상속됩니다. fstreamiostream에서 상속되며 istreamstream에서 상속됩니다. 일반적으로 ofstream은 출력 작업 (즉, 텍스트 파일 < < "hello") 만 지원하며 fstream은 출력 및 입력 작업을 모두 지원하지만 파일을 열 때 제공되는 플래그에 따라 다릅니다. 귀하의 예에서 열린 모드는 기본적으로 ios_base::in | ios_base::out입니다. ofstream의 기본 열기 모드는 ios_base::out입니다. 또한 ios_base::out은 항상 (심지어 명시 적으로 인수 모드로 설정되지 않은 경우에도) ofstream 객체에 대해 설정됩니다.

textfile은 출력 전용이고 ifstream은 입력 전용이고 fstream은 입력과 출력용입니다. 이것은 당신의 의도를보다 분명하게합니다.

+0

y! 대신 cppreference.com을 인용하십시오 –

+1

http://en.cppreference.com/w/cpp/io – ooga

+0

@ Cheersandhth.-Alf cppreference.com은 더 예쁘지만 google은'C++ fstream'에 대해 저에게 cplusplus.com을 돌려줍니다. cplusplus.com보다 cppreference.com의 다른 장점은 무엇입니까? –