流的奇怪问题.不能存储具有特定值的成员变量的对象

Weird problem with fstream. Cannot store objects with member variables having a certain value

本文关键字:变量 对象 成员 问题 不能 存储      更新时间:2023-10-16

当我尝试存储具有任何值为 13 或 26 或 7 的元素的对象,然后尝试读取此文件时,它只是给出垃圾值。其他值(如 1、64、78(随机值((不会发生这种情况。

我分别使用了ofstreamifstream来保持代码简单。我正在使用旧的编译器(Borland C++(,但我的朋友没有遇到此错误。

#include <iostream.h>
#include <conio.h>
#include <fstream.h>
class xyz
{
public:
int x;
};
void main()
{
xyz a;
a.x = 45; // replace by 45 or 78 it works. Replace by 13, 26 it shows garbage values.
ofstream of;
of.open("file.dat", ios::out||ios::binary);
of.write((char*)&a, sizeof(a));
of.close();
xyz b;
ifstream sf;
sf.open("file.dat", ios::in||ios::binary);
sf.read((char*)&b, sizeof(b));
sf.close();
cout<<b.x;
getch();
}

目前输出将为 45,但如果将其替换为 13 或 26,它将打印垃圾值。

sf.open("file.dat", ios::in||ios::binary);

||不会做你认为它做的事情。在这里,您需要使用按位或运算符,|,而不是逻辑运算符||

因此,由于此错误,您的文件实际上以文本模式打开,而不是以预期的二进制模式打开。

代码将二进制八位字节 13 和 26 写入文件并将其读回。八进制 13 和 26 由于其历史遗产,在 Microsoft Windows 上的文本文件中具有特殊含义。代码也无法检查read()的返回值和/或输入流的状态,这本来可以检测到此错误。

这是因为您的代码包含问题,最值得注意的是,您尝试使用||(逻辑/布尔OR(而不是|(按位OR(执行按位OR,后者用于像您一样将标志添加在一起。

其他需要注意的事情(尽管我不确定它们是问题的直接来源(: - 调用标准元素时忘记使用std::- 主要总是需要返回int

键入下次,启用更多编译器标志以帮助查找代码中的问题。 我不知道 turbo-c++,但在 g++ 中,您可以添加-Wall -Wextra以获取更多警告。 还有更多功能可供启用!

这是您的代码,其中包含我提到的一些更改

#include <fstream>
#include <iostream>
class xyz
{
public:
int x;
};
int
main()
{
xyz a;
a.x = 45;
std::ofstream of;
of.open("file.dat", std::ios::out | std::ios::binary);
of.write((char*)&a, sizeof(a));
of.close();
xyz b;
std::ifstream sf;
sf.open("file.dat", std::ios::in | std::ios::binary);
sf.read((char*)&b, sizeof(b));
sf.close();
std::cout << b.x;
}

请注意,如果您无法访问"最新"编译器(我假设您停留在一个版本上(,则有几个在线编译器允许您编译代码: - https://wandbox.org - https://gcc.godbolt.org/ -等

你的编码实际上不是正确的,这是基于你的代码的解释:

#include<iostream>
#include<fstream>
#include<ios>
using namespace std;
struct xyz{
int x;
};
int main(){
xyz a, b;
a.x=134;
fstream of;
of.open("file.dat"s, ios::out|ios::binary); // bitwise or
of.write((const char*)&a, sizeof(a));
of.close();

ifstream sf;
sf.open("file.dat"s, ios::in|ios::binary);
sf.read((char*)&b, sizeof(b));
sf.close();
cout<<b.x<<endl;
return 0;

};