简体   繁体   中英

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.
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 ). For the most part, just use ofstream (and ifstream for input).

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. 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. This is the value which Visual C++ (and maybe some other compilers) uses to fill uninitialized memory in debug mode. Your array isn't receiving this value from the file, this is the value which was inserted there when your memory was allocated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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