c++ - 为什么 Windows 不能读取超出 0x1A (EOF) 字符但 Unix 可以?

标签 c++ memory error-handling fstream eof

<分区>

Possible Duplicate:
Why failbit set when eof on read? Is there a way out?

我正在编写一个小程序,它在 Mac OS 和 Ubuntu(Unix...)上运行良好。该程序必须读取数据文件并将字节 (chars/unsigned chars) 和 memcpy() 分隔成 float 。这将包括采用以下四个值的过程,读取并将它们左移到 32 位 int 中,然后将 int 的内存复制到 float。像这样:

0x43 0x66 0x1A 0x79 -> read in int32 and memcpy() into float -> val = 230.103

As I said, this works fine for Unix, but Windows seems to interpret the char 0x1A as an end of file (EOF) error and stop reading in data. Why does Windows do such a thing and not Unix? And how could I turn it off?

I even tried error handling by looking at the ifstream itself and check if the EOL flag has been set. Then I would clear() the ifstream's error flags and continue reading (using get()) but the damn thing always returns the same EOF / 0x1A character and does not read in the next character.

EDIT: Added some code


ifstream input (PATH, ios::in);
if (input.is_open()) {
  unsigned int counter = 0;
  while (input.good()) {
    BYTE byte;
    byte = input.get();
    printf("%i, ", byte);
    counter++;
  }
  printf("\r%i, ", counter);
  input.close();
} else {
  printf("Can't open file!");
}

非常感谢任何帮助。

最大

最佳答案

使用 ifstream input (PATH, ios::in);,您可以(默认)文本模式打开文件。当以文本模式打开文件时,标准库对从文件读取的数据执行特定于平台的转换,以将平台的文本文件 native 格式映射到 C(和 C++)对文本文件的 View 。

对于类 unix 系统(包括 Mac OSX 和 Linux), native 文本格式与 C 和 C++ 查看文本的方式相同,因此不需要转换。

在 Windows 平台上,必须转换行尾('\n' 与字符序列 CR LF 相互转换),而 EOF 字符Windows 定义的 (1A) 必须被解释。

在其他系统上,可能需要更广泛的转换(例如,如果文本文件被指定为恰好 80 个字符的空格填充行,则实现将不得不生成 '\n' 读取 80 个字符后的字符本身,它可能会抑制一行中的尾随空格字符)。

关于c++ - 为什么 Windows 不能读取超出 0x1A (EOF) 字符但 Unix 可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13582804/

相关文章:

C++/Windows API - 无法找到 CreateWindow

c++ - Clang:将引用绑定(bind)到类型为 'const TClass' 的值会删除限定符

c++ - 'Guaranteed Copy Elision' (P0135, C++1z) 是否可能需要 ABI 损坏?

caching - 更大的缓存大小是否总是会提高性能?

c - glClear 函数 : Question about the parameters

c++ - 如何从 C++ 中的函数返回矩阵(板)?

c - 访问作为双指针传递给函数的 Typedef 结构指针。函数内部访问

R: 系统找不到指定的文件?

javascript - 加载文件后如何将 promise 错误传播到更高的 promise 级别?

php - 引用 - 这个错误在 PHP 中是什么意思?