opening "-" automatically yields stdout.
[oota-llvm.git] / lib / Support / raw_ostream.cpp
1 //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements support for bulk buffered stream output.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Support/raw_ostream.h"
15 using namespace llvm;
16
17 #if !defined(_MSC_VER)
18 #include <fcntl.h>
19 #else
20 #include <io.h>
21 #define open(x,y,z) _open(x,y)
22 #define write(fd, start, size) _write(fd, start, size)
23 #define close(fd) _close(fd)
24 #endif
25
26 // An out of line virtual method to provide a home for the class vtable.
27 void raw_ostream::handle() {}
28
29 //===----------------------------------------------------------------------===//
30 //  raw_fd_ostream
31 //===----------------------------------------------------------------------===//
32
33 /// raw_fd_ostream - Open the specified file for writing.  If an error occurs,
34 /// information about the error is put into ErrorInfo, and the stream should
35 /// be immediately destroyed.
36 raw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo) {
37   // Handle "-" as stdout.
38   if (Filename[0] == '-' && Filename[1] == 0) {
39     FD = STDOUT_FILENO;
40     ShouldClose = false;
41     return;
42   }
43   
44   FD = open(Filename, O_WRONLY|O_CREAT|O_TRUNC, 0644);
45   if (FD < 0) {
46     ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
47     ShouldClose = false;
48   } else {
49     ShouldClose = true;
50   }
51 }
52
53 raw_fd_ostream::~raw_fd_ostream() {
54   flush();
55   if (ShouldClose)
56     close(FD);
57 }
58
59 void raw_fd_ostream::flush_impl() {
60   if (OutBufCur-OutBufStart)
61     ::write(FD, OutBufStart, OutBufCur-OutBufStart);
62   HandleFlush();
63 }
64
65
66 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
67 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false) {}
68
69 // An out of line virtual method to provide a home for the class vtable.
70 void raw_stdout_ostream::handle() {}
71 void raw_stderr_ostream::handle() {}