如何在 c++ 中读取/写入无符号数组到 ifstream/ostream?
How to read/write unsigned array to ifstream/ostream in c++?
我有以下代码:
/*write to file*/
std::basic_ofstream<unsigned short> out(path, std::ios::out);
unsigned short *arr = new unsigned short[500];
for (int i = 0; i < 500; i++)
{
arr[i] = i;
}
out.write(arr, 500);
out.close();
/*read from file*/
unsigned short * data = new unsigned short[500];
std::basic_ifstream<unsigned short> rfile(path);
rfile.read(data, 500);
rfile.close();
简单地说,我将一个无符号的短数组写入文件,然后我读取它,但读取值是正确的,直到数组中的索引 25,之后值为 52685。
问题出在哪里?
首先,不要将basic_ofstream
的模板参数与非字符类型一起使用(即char
、wchar_t
、char16_t
或char32_t
(。在大多数情况下,只需使用ofstream
(和ifstream
进行输入(。
您的输入在第 25 个字符后停止的事实实际上表明您可能在 Windows 上,其中 ASCII 字符 26(替换字符(用于指示文本流的文件结尾。但是,您正在尝试读取和写入二进制数据,因此需要使用二进制标志打开文件。
/*write to file*/
std::ofstream out(path, std::ios::binary);
unsigned short *arr = new unsigned short[500];
for (int i = 0; i < 500; i++) {
arr[i] = i;
}
out.write((char const*)arr, 500 * sizeof(arr[0]));
out.close();
/*read from file*/
unsigned short * data = new unsigned short[500];
std::ifstream rfile(path, std::ios::binary);
rfile.read((char*)data, 500 * sizeof(data[0]));
rfile.close();
同样有趣的是,十六进制中的 52685 是0xCDCD。这是Visual C++(可能还有其他一些编译器(用于在调试模式下填充未初始化内存的值。您的数组没有从文件中接收此值,这是分配内存时插入的值。
相关文章:
- 使用无符号字符数组有效存储内存
- 无法在 Arduino 中uint8_t数组转换为无符号长整型数组
- 将无符号字符的向量存储在数组中会给我 std::bad_alloc
- 寻找一种更好的方法来表示无符号字符数组
- 将浮点数转换为无符号字符数组并打印出来
- 在函数中返回无符号字符数组,但不返回指针
- 如何在 C/C++ 中将无符号字符*转换为无符号字符数组?
- 如何返回实际值(在我的例子中是无符号字符数组)而不是来自 C++ 函数的指针?
- 字符数组到无符号字符 *
- 将字符串转换为无符号字符数组/字节数组
- 如何在给定文本中用字符数组替换符号
- 错误:无法从"元组<[...]、std::__1::元组<无符号长长、无符号长长>>"到"常量元组<[...],uint_type>"的可行转换
- 带有非默认构造类型的填充性std ::数组(无变量模板)
- 错误:"数组":符号不明确
- 如何在 C CLI 中从数组<无符号短>复制到无符号短 []?
- C++ 使用 char* 复制字符数组(无字符串库)
- 从数据文件读取到 2D 数组.无输出.C++
- 如何使用数组(无向量)将多个字符串文字传递给函数
- 如何工作与内存地址在C?它们是十六进数还是无符号整型
- 如何初始化c字符串数组(无stl)