在 C++ 中读取和写入二进制文件
我需要创建一个包含“名称”的文件,其中“名称”是一个字符串 - 字符数组 - 和“数据”,它是字节数组 - C++中的字符数组 - 但我面临的第一个问题是如何分离“名称”从“数据”?换行符在这种情况下可以工作(假设我的名称中没有“\n”),但我可以在“数据”部分中有特殊字符,所以无法知道它何时结束,所以我放了一个文件中数据之前的 int 值,其大小为“数据”! 我尝试使用以下代码执行此操作:
if((fp = fopen("file.bin","wb")) == NULL)
{
return false;
}
char buffer[] = "first data\n";
fwrite( buffer ,1,sizeof(buffer),fp );
int number[1];
number[0]=10;
fwrite( number ,1,1, fp );
char data[] = "1234567890";
fwrite( data , 1, number[0], fp );
fclose(fp);
但我不知道“int”部分是否正确,因此我尝试了许多其他代码,包括这个:
char buffer[] = "first data\n";
fwrite( buffer ,1,sizeof(buffer),fp );
int size=10;
fwrite( &size ,sizeof size,1, fp );
char data[] = "1234567890";
fwrite( data , 1, number[0], fp );
当我打开文件时,我在文件中看到 4 个“NULL”字符看到一个整数。这正常吗? 我面临的另一个问题是从文件中再次读取它!我尝试读取的代码根本不起作用:(我尝试使用“fread”,但我不确定是否应该使用“fseek”,或者它只是读取它后面的另一个字符。
我想到使用如下所示的类,然后编写并读回:
class Sign
{
public:
char* name;
int size;
char* data;
};
但这在 C++ 中并不是一件容易的事情!
我也尝试了以下方法:
void saveData(char* filename) {
fstream filestr;
int n;
n=10;
char* data= "1234567890";
filestr.open (filename, fstream::out | fstream::binary);
for (int j = 0; j<5 ; j++)
{
filestr << n;
for (int i = 0; i < n; i++) {
filestr << data[i];
}
}
filestr.close();
}
void readData(char* filename) {
fstream filestr;
int n =0;
filestr.open (filename, fstream::in | fstream::binary);
int m =0;
//while(!filestr.eof())
while(m<5)
{
filestr >> n;
char *data = new char[n];
for (int i = 0; i < n; i++) {
filestr >> data[i];
}
printf("data is %s\n",data);
m++;
}
filestr.close();
}
但是读取
时我也遇到了奇怪的字符
。对我有用的代码是这样的:
void saveData(char* filename) {
fstream filestr;
char * name = "first data\n";
int n;
n=10;
char* data= "asdfghjkl;";
filestr.open (filename, fstream::out | fstream::binary);
for (int j = 0; j<5 ; j++)
{
filestr << name;
filestr << strlen(data);
filestr << data;
}
filestr.close();
}
void readData(char* filename) {
fstream filestr;
int n =0;
filestr.open (filename, fstream::in | fstream::binary);
while(!filestr.eof())
{
string name;
getline(filestr,name,'\n');
printf("name is %s\n",name.c_str());
filestr >> n;
char *data = new char[n];
for (int i = 0; i < n; i++) {
filestr >> data[i];
}
printf("n is%d\ndata is %s\n",n,data);
}
filestr.close();
}
但是阅读时的问题是:
1-(我不认为这是一个真正的问题)除了实际数据之外,它还打印其他字符。 2-在readData
函数上,我得到输出6次(上次我将每个字段都作为空字段),而我只写了5强>次!有人知道这是为什么吗?与 while(!filestr.eof())
相关吗?
感谢您的帮助
I need to make a file that contains "name" which is a string -array of char- and "data" which is array of bytes -array of char in C++- but the first problem I faced is how to separate the "name" from the "data"? newline character could work in this case (assuming that I don't have "\n" in the name) but I could have special characters in the "data" part so there's no way to know when it ends so I'm putting an int value in the file before the data which has the size of the "data"!
I tried to do this with code as follow:
if((fp = fopen("file.bin","wb")) == NULL)
{
return false;
}
char buffer[] = "first data\n";
fwrite( buffer ,1,sizeof(buffer),fp );
int number[1];
number[0]=10;
fwrite( number ,1,1, fp );
char data[] = "1234567890";
fwrite( data , 1, number[0], fp );
fclose(fp);
but I didn't know if the "int" part was right, so I tried many other codes including this one:
char buffer[] = "first data\n";
fwrite( buffer ,1,sizeof(buffer),fp );
int size=10;
fwrite( &size ,sizeof size,1, fp );
char data[] = "1234567890";
fwrite( data , 1, number[0], fp );
I see 4 "NULL" characters in the file when I open it instead of seeing an integer. Is that normal?
The other problem I'm facing is reading that again from the file! The code I tried to read didn't work at all :( I tried it with "fread" but I'm not sure if I should use "fseek" with it or it just read the other character after it.
I thought of using a class as following and then writing and reading it back:
class Sign
{
public:
char* name;
int size;
char* data;
};
but that was not an easy thing in C++ !!
I also tried the following:
void saveData(char* filename) {
fstream filestr;
int n;
n=10;
char* data= "1234567890";
filestr.open (filename, fstream::out | fstream::binary);
for (int j = 0; j<5 ; j++)
{
filestr << n;
for (int i = 0; i < n; i++) {
filestr << data[i];
}
}
filestr.close();
}
void readData(char* filename) {
fstream filestr;
int n =0;
filestr.open (filename, fstream::in | fstream::binary);
int m =0;
//while(!filestr.eof())
while(m<5)
{
filestr >> n;
char *data = new char[n];
for (int i = 0; i < n; i++) {
filestr >> data[i];
}
printf("data is %s\n",data);
m++;
}
filestr.close();
}
But the reading didn't work either.
On reading I'm getting strange characters.
So far the code that works for me is this:
void saveData(char* filename) {
fstream filestr;
char * name = "first data\n";
int n;
n=10;
char* data= "asdfghjkl;";
filestr.open (filename, fstream::out | fstream::binary);
for (int j = 0; j<5 ; j++)
{
filestr << name;
filestr << strlen(data);
filestr << data;
}
filestr.close();
}
void readData(char* filename) {
fstream filestr;
int n =0;
filestr.open (filename, fstream::in | fstream::binary);
while(!filestr.eof())
{
string name;
getline(filestr,name,'\n');
printf("name is %s\n",name.c_str());
filestr >> n;
char *data = new char[n];
for (int i = 0; i < n; i++) {
filestr >> data[i];
}
printf("n is%d\ndata is %s\n",n,data);
}
filestr.close();
}
but the problems in reading are:
1- (I don't think it's a real problem) it prints other characters in addition to the actual data.
2- on readData
function I get the output 6 times (in the last time I get every field as an empty field) while I have written only 5 times! Anyone knows why is that? is that related to while(!filestr.eof())
??
Thanks for help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您以二进制格式进行的写入/读取应该像这样工作(这里
read_num
将在此读取序列之后包含10
)。另外要提一下,这种写法不是C++的方式,而是C的方式。 C++的文件操作方式是流,见下面的示例:
First, your writing / reading in binary format should work like this (here
read_num
would contain10
after this reading sequence).Also to mention, this way of writing is not the C++ way, but is the C way. C++ way of file operations means streams, see the following sample:
好吧,您的代码存在一些问题:
该函数定义如下:
因此您将在缓冲区中发送信息,说它的大小为 1,并且 sizeof(buffer) 的计数。这可能对某些事情有用,但通常是倒退的。尝试使用:
这与字符宽度无关,并且没有您需要担心的常量值(它基本上适用于任何字符串)。
其中的另一件小事:
您有一个整数,因此您只需要使用:
如果在更改后遇到
fwrite
错误,请使用此调用:这会将一个整数的值写入文件。
修复该问题后,看看您的代码是否有效。纠正这些调用后,排除故障肯定会更容易。 :)
另外,如果您计划使用字段长度(以整数形式写入文件),您将需要设置某种系统来读取长度,然后读取数据,并且您可能应该有一个长度对于每个字段。使用类绝对是处理这个问题的最简单方法。
编辑:
您可能想要使用结构和函数而不是类,或者可以使用带有方法的类。这并不重要,两者都很简单。结构/函数:
Well, a few issues with your code:
The function is defined as this:
So you're sending the information in buffer, saying it has a size of 1, and count of sizeof(buffer). That might work for some things, but is just generally backwards. Try using:
That's both character-width independent and has no constant values you need to worry about (it will work for basically any string).
Another minor thing in this:
You have a single integer, so you need only use:
If you run into errors with
fwrite
after changing it, use this call:That will write the value of one integer to the file.
After you fix that up, see if your code works. It will certainly be easier to troubleshoot with those calls corrected. :)
Also, if you're planning on using field lengths (written as ints into the file), you're going to want to set up some kind of system to read the length, then data, and you should probably have a length for each field. Using a class is definitely the easiest way to handle that.
Edit:
You may want to use a struct and function instead of a class, or you could use a class with methods. It doesn't really matter, both are pretty simple. Struct/func: