2016-09-05 4 views
15

설명 할 수없는 fstreamoftream 사이에 다른 동작이 나타납니다.std :: fstream이 파일에 쓰지 않는 이유는 무엇입니까?

내가 사용하는 경우 fstream, 아무 일도 일어나지 않는다, 즉 어떤 파일이을 작성되지 않습니다 :

int main() 
{ 
    std::fstream file("myfile.txt"); 
    file << "some text" << std::endl; 
    return 0; 
} 

하지만 oftreamfstream을 변경할 때, 그것은 작동합니다.

왜?

fstream CTOR의 두 번째 인수는 ios_base::openmode mode = ios_base::in | ios_base::out이며 파일이 읽기 - 쓰기 모드로 열렸다고 생각하니?

+3

작업을해야 그 . 버퍼링? 우리는 완전한 [mcve]가 필요하다고 생각합니다. –

+1

이 코드가있는 함수가 있는데 작동하지 않습니다. 나는 더 쓸 일이 없다. MVS2015. – Narek

+0

파일에 글을 올린 경우 너무 일찍 확인한 것일 수 있습니다. "close()"는 fstream을 파기 할 때만 호출됩니다 – CppChris

답변

27

ios_base::in requires the file to exist.

ios_base::out으로 제공하면 파일이 존재하지 않는 경우에만 만들어집니다.

+--------------------+-------------------------------+-------------------------------+ 
| openmode   | Action if file already exists | Action if file does not exist | 
+--------------------+-------------------------------+-------------------------------+ 
| in     | Read from start    | Failure to open    | 
+--------------------+-------------------------------+-------------------------------+ 
| out, out|trunc  | Destroy contents    | Create new     | 
+--------------------+-------------------------------+-------------------------------+ 
| app, out|app  | Append to file    | Create new     | 
+--------------------+-------------------------------+-------------------------------+ 
| out|in    | Read from start    | Error       | 
+--------------------+-------------------------------+-------------------------------+ 
| out|in|trunc  | Destroy contents    | Create new     | 
+--------------------+-------------------------------+-------------------------------+ 
| out|in|app, in|app | Write to end     | Create new     | 
+--------------------+-------------------------------+-------------------------------+ 

PS :

몇 가지 기본 오류 처리는 무슨 일이 일어나고 있는지 이해하는데 유용 할 수있다 :

#include <iostream> 
#include <fstream> 

int main() 
{ 
    std::fstream file("triangle.txt"); 
    if (!file) { 
    std::cerr << "file open failed: " << std::strerror(errno) << "\n"; 
    return 1; 
    } 
    file << "Some text " << std::endl; 
} 

출력 :

C:\temp> mytest.exe 
file open failed: No such file or directory 

C:\temp> 
관련 문제