简体   繁体   English

如何在C ++中将无符号数组读/写到ifstream / ostream?

[英]How to read/write unsigned array to ifstream/ostream in c++?

I have below code : 我有以下代码:

/*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();

Simply i write a unsigned short array to file then i read that but read values are right until index 25 in array and after that the values are 52685. 只需将一个无符号的短数组写入文件,然后读取,但读取的值正确,直到数组中的索引25为止,之后的值为52685。
Where is the problem? 问题出在哪儿?

First of all, don't use the template parameter of basic_ofstream with a non character type (ie char , wchar_t , char16_t or char32_t ). 首先,不要使用非字符类型的basic_ofstream模板参数(即charwchar_tchar16_tchar32_t )。 For the most part, just use ofstream (and ifstream for input). 在大多数情况下,只需使用ofstream (以及ifstream作为输入)。

The fact that your input stops after the 25th character is actually a clue that you are probably on Windows, where ASCII character 26, the Substitute character , is used to indicate end of file for text streams. 您输入停止在第25个字符之后的事实实际上是您可能在Windows上的线索,其中ASCII字符26( 替换字符 )用于指示文本流的文件结尾。 You are trying to read and write binary data though, so you need to open your file with the binary flag. 但是,您尝试读取和写入二进制数据,因此需要使用二进制标志打开文件。

/*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();

Also interesting to note, 52685, in hexadecimal is 0xCDCD. 同样有趣的是,十六进制的52685是0xCDCD。 This is the value which Visual C++ (and maybe some other compilers) uses to fill uninitialized memory in debug mode. 这是Visual C ++(也许还有其他一些编译器)用来在调试模式下填充未初始化内存的值。 Your array isn't receiving this value from the file, this is the value which was inserted there when your memory was allocated. 您的数组未从文件接收此值,这是分配内存时在其中插入的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM