类似于 istringstream 的ferror(FILE *)?

发布于 2024-11-04 22:41:20 字数 788 浏览 1 评论 0原文

我目前正在尝试将使用 C 样式 FILE* 解析文件的代码移植到 C++ 样式 istringstream。我的程序并行运行,我想 1)仅在第一个 CPU 上读入文件,2)以字符串形式将内容广播到所有其他 CPU,3)让每个 CPU 解析该字符串。

旧版本的解析器基本上执行以下操作:

while (!done) {
    int c = fgetc(infile);
    if (EOF == c) {
        if (ferror(infile)) {
            // throw some error
        }
        return;
    }
    // continue parsing
}

infile 是一个 FILE*。我现在尝试转换代码如下:

while (!done) {
    char cchar = iss.get(); int c = int(cchar);
    if (EOF == c) {
        if ((iss.rdstate() & ifstream::failbit ) != 0 ) {
            // throw some error
        }
        return;
    }
    // continue parsing
}

iss 是一个 istringstream。问题是,当前在 C++ 版本中,当达到 EOF 时总是抛出错误。所以我没有正确的类比“ferror”。有人能帮我吗?

塞巴斯蒂安

I'm currently trying to port a code from parsing a file using a C-style FILE* to a C++-style istringstream. My program runs in parallel and I would like to 1) read in the file only on the first CPU, 2) broadcast the contents in string-form to all other CPUs and 3) have each CPU parse the string.

The old version of the parser essentially does the following:

while (!done) {
    int c = fgetc(infile);
    if (EOF == c) {
        if (ferror(infile)) {
            // throw some error
        }
        return;
    }
    // continue parsing
}

infile is a FILE*. My attempt to convert the code is now the following:

while (!done) {
    char cchar = iss.get(); int c = int(cchar);
    if (EOF == c) {
        if ((iss.rdstate() & ifstream::failbit ) != 0 ) {
            // throw some error
        }
        return;
    }
    // continue parsing
}

iss is an istringstream. The problem is that currently an error is always thrown in the C++ version when EOF is reached. So I don't have the correct analogogn to ferror. Can anyone help me with that?

Sebastian

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月打碎记忆 2024-11-11 22:41:20

当您尝试读取某些内容但已到达文件末尾时,将始终设置失败位。如果您尝试读取某些内容,但尚未到达文件末尾,但文件中的数据无法转换为目标类型(例如,您尝试读取 int,但文件包含“K”)。

The failbit will always be set when you try to read something but have reached the end of the file. It will also be set if you try to read something, and haven't reached the end of the file, but the data in the file couldn't be converted to the target type (e.g., you try to read an int, but the file contains "K").

各自安好 2024-11-11 22:41:20

如果流失败,并且您可能期望 EOF,只需测试它:

// read stuff here
if ( iss.eof() ) {
    // failed, but eof is ok
}
else {
    // a real error
}

eof 位仅由文件末尾设置,而不是由其他问题设置。

If the stream has failed, and you might be expecting an EOF, simply test for it:

// read stuff here
if ( iss.eof() ) {
    // failed, but eof is ok
}
else {
    // a real error
}

the eof bit is only set by end of file, not by other problems.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文