当一个ofstream object.open()被注释掉时会发生什么?

时间:2015-12-29 19:00:55

标签: c++ iostream fstream

private void sendMessage(String message, int relaisId, long timestamp) {

    try {
        if (connCount > 50) {
            s = new Socket(ip, port); //RUN NORMALLY: java.net.ConnectException: Connection refused: connect
            connCount=0;
        }
        outputStream = s.getOutputStream();

        outputStream.write(message.getBytes());
        outputStream.write(new byte[]{0});//DEBUG: java.net.SocketException: Connection reset by peer: socket write error
        outputStream.flush();
        connCount++;
    } catch (UnknownHostException ex) {
        logger.error("Host not found: " + ip + ":" + port, ex);
        connCount=51;
        retryMessage(message, relaisId, timestamp);// basically sleep 3s then call sendMessage
    } catch (IOException ex) {
        logger.error("Error at Relais No. " + relaisId + ": " + ip + ":" + port, ex);
        connCount=51;
        retryMessage(message, relaisId, timestamp); // basically sleep 3s then call sendMessage
    } finally {
        try {
            if (connCount > 50 && s != null) {
                s.close();                    
            }
        } catch (IOException ex) {
            logger.error("IOException", ex);
        }
    }
}

当我使用 ifstream 中的 somefile.txt 阅读时,使用 anotherfile.txt > ofstream ,一切正常,但假设我注释掉#include<iostream> #include<fstream> #include<string> #include<vector> using namespace std; int main(){ ofstream out; ifstream in; out.open("The Necessary Death of Charlie Countryman2.srt"); if (out.fail()) { perror("The Necessary Death of Charlie Countryman2.srt"); } in.open("The Necessary Death of Charlie Countryman.srt"); if (in.fail()) { perror("The Necessary Death of Charlie Countryman.srt"); } vector<string> input; string inc; while (getline(in, inc)) { input.push_back(inc); } for (int k = 0; k < input.size(); k++) { out << input[k] << endl; } return 0; } 并执行代码,没有错误,当我打开 anotherfile.txt 它是空的。

我的问题是在

期间
out.open("anotherfile.txt")

会发生什么?

发送给for (int k = 0; k < input.size(); k++) { out << input[k] << endl; } 的地点或内容是什么?如果它是 cout ,则进入命令提示符,如果input[k]未被注释,则转到anotherfile.txt。

4 个答案:

答案 0 :(得分:2)

每个<<操作都会失败,就是这样(那是(1)所有这一切。)

(1)可以将流设置为在失败时抛出异常的模式,但这不是默认值。默认情况下,默认会忽略失败。除了设置了失败状态位之外,您可以使用fail()或转换为bool来检查。 功能

答案 1 :(得分:2)

我假设out被声明为ostream(或ofstream之类的子类)。当您注释掉out.open(...)行时,out会被初始化为已关闭的文件。因此,当您尝试写入时,没有任何反应,并且注入失败......但无法测试它是否成功!

如果您使用以下方法进行测试:

    for (int k = 0; k < input.size(); k++) {
        out << input[k] << endl;
        if out.fail() {
            // process error condition...
        }
    }

你会传入错误条件分支,并且能够知道注入没有发生。

答案 2 :(得分:2)

ofstream使用此operator<<签名

basic_ostream& operator<<( std::basic_streambuf<CharT, Traits>* sb);

来自cpppreferenceoperator<<,8)

  

构造并检查sentry对象后,检查sb是否为空指针。如果是,则执行setstate(badbit)并退出。

您可以通过

轻松检查
#include <iostream>
#include <fstream>

int main()
{
    std::ofstream sink;
    //sink.open("/dev/null");

    sink << "check state";

    switch(sink.rdstate())
    {
        case std::ios_base::failbit:
            std::cout << "stream state is failbit\n";
            break;
        case std::ios_base::goodbit:
            std::cout << "stream state is goodbit\n";
            break;
        case std::ios_base::eofbit:
            std::cout << "stream state is eofbit\n";
            break;
        case std::ios_base::badbit:
            std::cout << "stream state is badbit\n";
            break;
        default:
            break;
    }

    return 0;
}

Prints:流状态为badbit

答案 3 :(得分:1)

outstd::ostream类型的对象,同样std::cout是一个类型为std::ostream的对象,它位于全局命名空间中(它在您的开头可用)程序)。

类型为std::ostream的对象(输出流,包括像std::ofstream一样扩展它的子类),它们的<<运算符被重载。

cout<<"hello";这种方式与std::cout.operator<<("Hello World");

相同

请注意,重载的<<运算符会返回对ostream对象的引用,因此cout<<"hi" << " there";基本上是

std::cout.operator<<("hi").operator<<(" there"));

在写入之前,您需要打开任何输出文件流。通过这样做,您正在向操作系统调用一个系统调用,使您可以访问这些文件,以便您可以写入文件。否则,您正在尝试写入您的进程无权写入的已关闭文件。

您不必为std::cout明确执行此操作,但您应该打开自己的输出文件流。

不要忘记关闭打开的文件!!

相关问题