大佬教程收集整理的这篇文章主要介绍了C++二进制文件读写(read和write)详解,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
<<
在输出期间提供数字的自动格式化。同样,流提取操作符 >>
提供数字输入的解析。例如,来看以下程序片段:ofstream file("num.dat"); short x = 12 97; file << x;最后一个语句将 x 的内容写入文件。然而,当数字被写入时,它将被存储为字符 '1'、'2'、'9' 和 '7',如图 1 所示。
file.open("stuff.dat",ios::out | ios::binary);
请注意,ios::out 和 ios::binary 标志使用|运算符联合加入到语句中,这导致文件以输出和二进制模式打开。write(addressOfBuffer,numberOfBytes);
write 成员函数不会区分缓冲区中的整数、浮点数或其他类型;它只是将缓冲区视为一个字节数组。由于 C++ 不支持指向字节的@L_197_44@,因此 write 函数原型将指定缓冲区的地址是指向 char 的指针:write(char *addressOfBuffer,int numberOfBytes);
这意味着当调用 write 时,需要告诉编译器将缓冲区的地址解释为指向 diar 的指针。要做到这一点,可以使用称为 reinterpret_cast 的特殊形式的类型转换。简单地说,reinterpret_cast 可用于强制编译器解释一个类型的位,就好像它们定义了一个不同类型的值。
double d = 45.9;
double *pd = &d;
char *pChar;
//将指向double的指针转换为指向char的指针
pChar = reinterpret_cast<char *>(pd);
reinterpret_cast<TargetType>(value);
以下是使用 write 将一个 double 类型数字和一个包含 3 个 double 类型数字的数组写入文件的示例:
double dl = 45.9;
double dArraY[3] = { 12.3,45.8,19.0 };
ofstream outFile("stuff.dat",ios::binary);
outFile.write(reinterpret_cast<char *>(&dl),sizeof(dl));
outFile.write(reinterpret_cast<char *>(dArray),sizeOf(dArray));
char ch = 'X';
char chararray[5] = "Hello";
outFile.write(&ch,sizeof(ch));
outFile.write(charArray,sizeof(charArray));
read(addressOfBuffer,numberOfBytes)
必须使用 reinterpret_cast 将缓冲区的地址解释为指向 char 的指针。可以通过调用输入流上的 fail() 成员函数来发现指定的字节数是否成功读取。//This program uses the write and read functions. #include <iostream> #include <fstream> using namespace std; int main() { //File object used to access file fstream file("nums.dat",ios::out | ios::binary); if (!filE) { cout << "Error opening file."; return 0; } //Integer data to write to binary file int buffer[ ] = {1,2,3,4,5,6,7,8,9,10}; int size = sizeof(buffer) / sizeof(buffer[0]); // Write the data and close the file cout << "Now wriTing the data to the file.\n"; file.write(reinterpret_cast<char *>(buffer),sizeof(buffer)); file.close (); // Open the file and use a binary read to read contents of the filE into an array file.open("nums.dat",ios::in); if (!filE) { cout << "Error opening file."; return 0; } cout << "Now reading the data BACk into memory.\n"; file.read(reinterpret_cast<char *>(buffer),sizeof (buffer)); // Write out the array entries for (int count = 0; count < size; count++) cout << buffer[count] << " "; // Close the file file.close (); return 0; }程序屏幕输出:
Now wriTing the data to the file.
Now reading the data BACk into memory.
1 2 3 4 5 6 7 8 9 10
int buffer[ ] = {1,10};
int size = sizeof(buffer)/sizeof(buffer[0]);
以上是大佬教程为你收集整理的C++二进制文件读写(read和write)详解全部内容,希望文章能够帮你解决C++二进制文件读写(read和write)详解所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。