从二进制文件中读取字符 [英] Read chars from a binary file

查看:104
本文介绍了从二进制文件中读取字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。我正在尝试编写和读取二进制文件,当我尝试加载包含字符的数据时遇到一些问题。



Hello. I'm trying to write and read from a binary file and I having some problems when I try to load the data that contains chars.

 struct user {
	char *username;
	char * password;
	unsigned int ID;
 };


test_usernames_c.open("users_c.dta", ios::binary | ios::out);
user *default_user;
default_user = new user;

default_user->username = new char[7];
strcpy_s(default_user->username,7, "user11");

test_usernames_c.write((const char*)&default_user->username, 7);
//I hardcoded the size just to make sure 


test_usernames_c.close();

char *usernameX;
usernameX = new char[7];

test_usernames_c.seekg(pos_file, ios::beg);
test_usernames_c.read((char*)&usernameX, sizeof(char) * 7);





当我在代码末尾读取文件时,我得到了正确的结果但是我得到了CORRUPTED STACK并且Visual Studio抛出异常(运行时检查失败#2 - 变量'usernameX'周围的堆栈已损坏。)



你能告诉我如何更正代码或我做错了什么?如果我尝试读取用户结构中的数据它可以工作,但我不明白为什么,因为我以相同的方式在结构中启动char *和独立的usernameX char *。



When I read the file at the end of the code I get the correct result but I get CORRUPTED STACK and Visual Studio throws an exception (Run-Time Check Failure #2 - Stack around the variable 'usernameX' was corrupted.)

Can you please tell me how to correct the code or what Im doing wrong? If I try to read the data in a user struct it works but I dont understand why since I initiate the char* in the struct and the standalone usernameX char* in the same way.

推荐答案

看看cplusplus网站。它们有:



Look at cplusplus website. They have:

char * buffer = new char [length];

    std::cout << "Reading " << length << " characters... ";
    // read data as a block:
    is.read (buffer,length);





你不需要这个:



you don't need this:

(char*)&





可以解决您的问题吗?



does that solve your problem?


您的缓冲区寻址是错误的,它应该是:

Your buffer addressing is wrong, it should be:
test_usernames_c.write(default_user->username, 7); // username is already a pointer
//I hardcoded the size just to make sure 

test_usernames_c.close();
 
char *usernameX;
usernameX = new char[7];
 
test_usernames_c.seekg(pos_file, ios::beg);
test_usernames_c.read(usernameX, sizeof(char) * 7); // usernameX is also a pointer


这篇关于从二进制文件中读取字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆