fread()二进制模式在c++; 我在C++中编码时遇到了 Frad()/Cuff>函数的问题。 目标是以二进制模式打开文件,以便使用以下命令进行写入: fopen_s(&filename,filelocation,“wb”),使用fwrite(&buffer,size\u of_read,count,filename)精确地写入字符串和int,然后将数据读回其他变量(请注意,在同一个程序中从同一个文件写入然后读取数据似乎很愚蠢,但这只是出于测试目的,因为我正在处理的项目严格基于加密,而这是其中的一个模块)

fread()二进制模式在c++; 我在C++中编码时遇到了 Frad()/Cuff>函数的问题。 目标是以二进制模式打开文件,以便使用以下命令进行写入: fopen_s(&filename,filelocation,“wb”),使用fwrite(&buffer,size\u of_read,count,filename)精确地写入字符串和int,然后将数据读回其他变量(请注意,在同一个程序中从同一个文件写入然后读取数据似乎很愚蠢,但这只是出于测试目的,因为我正在处理的项目严格基于加密,而这是其中的一个模块),c++,io,C++,Io,这是我的密码: int x = 1; // this is piece of data to write to the file FILE *src; // the file variable that I am using string text = "byebye"; // this happens to be the piece of data

这是我的密码:

int x = 1;                              // this is piece of data to write to the file
FILE *src;                              // the file variable that I am using
string text = "byebye";                 // this happens to be the piece of data
src = fopen("F:\\_log.log", "wb");      // open file in binary write mode
fwrite(&text, 1, 7, src);               // that's 7 because of 6 characters plus '\0'
fwrite(&x, 4, 1, src);                  // 4 bytes for int ---> writing x=1 to file
text.clear();                           // for verification purpose
fclose(src);
src = fopen("F:\\_log.log", "rb");
int y = 0;                              // this is the int that will contain read data
string read;                            // string that contains read data
fread(&read, 1, 7, src);                // read the data and store in read
fread(&y, 4, 1, src);                   // read the stored int into y
cout << "string is : " << read << "\nNumber is : " << y << endl;
编号为:1
语句清除第一个
y
为零,但文件中的数据已成功读取并存储在
y
中,然后转到
1

但是,如果整数被正确读取,那么为什么字符串
read
另外,
text
read
中似乎存在同步,因为如果我将命令
text.clear();
更改为
text=“higuys”
,则输出为:

string is : higuys
Number is : 1
我如何解决这个问题?(完全无法理解该代码到底在处理什么…)

其他信息(尽管可能没有多大用处):

操作系统:Windows 10

IDE:代码块(也在visual studio中试用)

编译器:GNU GCC

调试器:GDB

我尝试使用
perror();
cout等技巧检查是否有任何错误,您需要进行更改

string read;

string是一个类而不是缓冲区,因此不能指定string对象的地址


如果程序不仅仅针对固定的7字节字符串,而且不仅仅针对C(您将问题标记为C++)你应该考虑使用IFStruts/OfString和String并使用运算符编写/读取../P>不能用<代码> Stry< /Cord>编写<代码> STD::String < /Cord>对象,也不能用<代码> Frad 来读取它。实际上没有任何复杂的对象。它将不起作用。你可能想搜索并阅读序列化。您想知道为什么不能像这样编写
std::string
对象,这是因为基本上
std::string
对象包含的是字符串长度和指向实际字符串的指针,编写指向文件的指针将不会很好地工作。此外,您不需要将null终止字符写入文件e的大小已经是已知的。那么,我是否应该尝试将字符串转换为一个字符数组,然后写入/读取它?这是解决问题的一种方法,但如果字符串的长度可以是可变的,则还需要存储长度,以便知道要读取多少(或者存储终止符,然后逐字节读取)。这是序列化字符串的一种方法。哦,您实际上不需要一个新数组来实现此目的,您已经有了一个“数组”,可以使用例如
text.c_str()
(在读取时不能使用,但是
&如果事先设置大小,text[0]
应该可以使用)你的标题提到C++,但是你的代码并不反映这个。我建议使用C++,虽然我正在考虑输入一个字符串,然后将它转换成<代码> char [String。长度];< /Cord>,这是因为:由于某种原因,当空白被存储到<代码> char []
它似乎没有固定住它,当它用
cout@Wormhole当然,您的字符串可以包含空格。也许您可以使用其他函数(scanf)读取它,该函数在第一个空格处停止!?
string read;
char read[7];