我的程序不是以二进制格式保存数据 [英] My program is not saving data in binary format

查看:55
本文介绍了我的程序不是以二进制格式保存数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//I made a program as below

#include<iostream.h>
#include<stdio.h>
#include<fstream.h>
void main()
{
    char name[24];
    cout << "enter string :";
    gets(name);
    ofstream fout;
    fout.open("bin_data", ios::out|ios::binary);
    fout.write((char*)&name, 10);
    fout.close();
}





此代码可以保存10个字的单词。但是当我通过turbo c ++ v4.5编译这段代码时,我发现了这一点。当我输入1或2个字母单词并打开bin_data文件时,它以文本格式保存(忽略垃圾值),但是当我输入3到7个字母长的单词并打开bin_data文件时,它以二进制格式保存(如凤凰东方宾馆)。并且以文本格式再次以9和10字母的单词.....任何人都可以告诉我原因...?

请按照我上面提到的编译并运行程序并回答



This code can save a word of 10 char. But when I compile this code by turbo c++ v4.5 I find that. When I input 1 or 2 letter word and open bin_data file it saves in text format(ignore garbage value) but when I input a word of 3 to 7 letter long and open bin_data file it saves in binary format(like 凤凰东方宾馆). and in 9 and 10 letter word again in text format..... Can anyone tell me the reason...?
Please compile and run program as I mentioned above and answer

推荐答案

你的程序实际上以二进制格式保存(如果你在二进制文件中写明文,它将包含,纯文本)。

你可能会看到奇怪的输出(你称之为二进制),具体取决于你用来检查文件的应用程序。
Your program actually does save in binary format (if you write plain text in a binary file the it will contain, well, plain text).
You may see strange output (you call it 'binary') depending on the application you use to inspect the file.


如果你正确地检查文件内容,你会发现它们和你一样编写它们。问题是你告诉系统总是写10个字符而不管文本的实际长度。当你用记事本打开文件时它会尝试无花果找出内容是什么,并且在某种组合下它认为它是Unicode,因此将其显示为奇怪的字符。
If you inspect the file contents properly you will find that they are exactly as you have written them. The problem is that you are telling the system to always write 10 characters regardless of the actual length of your text. When you open the file with Notepad it tries to figure out what the content is and with certain combinations it thinks it is Unicode and so displays it as strange characters.


这篇关于我的程序不是以二进制格式保存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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