类似于 istringstream 的ferror(FILE *)?
我目前正在尝试将使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您尝试读取某些内容但已到达文件末尾时,将始终设置失败位。如果您尝试读取某些内容,但尚未到达文件末尾,但文件中的数据无法转换为目标类型(例如,您尝试读取
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").如果流失败,并且您可能期望 EOF,只需测试它:
eof 位仅由文件末尾设置,而不是由其他问题设置。
If the stream has failed, and you might be expecting an EOF, simply test for it:
the eof bit is only set by end of file, not by other problems.