Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
//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();
}


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
Posted
Updated 12-Nov-15 19:24pm
v3
Comments
[no name] 13-Nov-15 1:07am    
The problem is your reasoning. You have not given an example of input and output. What are you using to view the file?
[no name] 13-Nov-15 2:07am    
U put any input like "as" it will be saved in text format but when I input like "adfghjj" it will be saved in binary format ( like 都很风)
[no name] 13-Nov-15 3:22am    
You have ignored what I asked. You must be precise. The only way your question will have any meaning is if you show us the input in hex and the output in hex. If you do that you may find that you have no question.
http://superuser.com/questions/369231/why-dont-you-see-binary-code-when-you-open-a-binary-file-with-text-editor

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.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 13-Nov-15 2:54am    
Of course, a 5. I would add: there is no such thing as non-binary file. Text files are binary, too. :-)
—SA
CPallini 13-Nov-15 2:59am    
Thank you.
Yes, there is just the Windows weird 'open mode' terminology that brings confusion.
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.
 
Share this answer
 
Comments
Jochen Arndt 13-Nov-15 4:16am    
Indeed. My 5.
To avoid this, the name buffer can be initialised with zeroes or spaces.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900