Difference Between C++ Text File and Binary File - GeeksforGeeks (2024)

Skip to content

Difference Between C++ Text File and Binary File - GeeksforGeeks (1)

Last Updated : 19 Feb, 2023

Summarize

Comments

Improve

Suggest changes

Like Article

Like

Save

Report

A text file is the one in which data is stored in the form of ASCII characters and is normally used for storing a stream of characters. Text files are organized around lines, each of which ends with a newline character (‘\n’). The source code files are themselves text files.

A binary file is the one in which data is stored in the file in the same way as it is stored in the main memory for processing. It is stored in binary format instead of ASCII characters. It is normally used for storing numeric information (int, float, double). Normally a binary file can be created only from within a program and its contents can be read only by a program.

Text File vs Binary File

The following are some of the differences between text files and binary files.

S. No.Text fileBinary File
1.The text files can easily be transferred from one computer system to another.Binary files cannot easily be transferred from one computer system to another due to variations in the internal variations in the internal representation which varies from computer to computer.
2.It stores data using ASCII format i.e. human-readable graphic characters.It stores data in binary format i.e. with the help of 0 and 1.
3.These files are easily readable and modifiable because the content written in text files is human readable.
Content written in binary files is not human-readable and looks like encrypted content.
These files are not easily readable and modifiable because thecontent written in binary files is not human-readable and it is encrypted content.
4.These files create portability problems.These files are easily portable.
5.

Text files save the data by converting each digit in data into ASCII format which will take up much of the space as compared to the required one.

For example, the number 546378 is an integer that should occupy 4 bytes in the disk but it will occupy 6 bytes, 1 byte for each digit in the number.

These save memory because the data of any type will get stored in memory as per its memory size.

For example, any integer number irrespective of individual digits in the number will be stored by consuming 4 bytes.

6.Any file is by default text file.The ios:: binary mode has to be used with binary files while opening them.
7.Error in a textual file can be easily recognized and eliminated.Error in a binary file corrupts the file and is not easily detected.
8.In a text file, a new line character is first converted to a carriage return-line feed combination and then written to the disk. Vice versa happens when a line is read from the text file.In binary file, no such conversion from newline to carriage return-line feed combination is done.
9.In a text file, a special character with ASCII code 26 is inserted at the end of the file. This character signals the EOF to the program when encountered.There is no such special character in the binary file to signal EOF.
10.Text files are used to store data more user friendly.Binary files are used to store data more compactly.
11.Mostly .txt and .rtf are used as extensions to text files.Can have any application defined extension.

C++

#include<iostream>

#include<fstream>

using namespace std;

int main() {

fstream FileName;

FileName.open("FileName.txt", ios::out);

if (!FileName) {

cout<<" Error while creating the file ";

}

else {

cout<<"File created and data got written to file";

FileName<<"This is a blog posted on Great Learning";

FileName.close() ;}

return 0 ;

}

Output

File created and data got written to file

Code explanation :

1. The input/output stream is handled by the iostream library in this case.
2. Additionally, we have a library called fstream that manages files.
making an object of the fstream class with the name “FileName” on it.
3. Applying the open() function to the previously constructed object will allow us to create a new file with the mode set to “out,” allowing us to write data into the file.
4. To verify the creation of the file, we utilise the ‘if’ expression.
5. if the file is missing, prints the message to the terminal.
6. if the file is created or existing, prints the message to the console.
7. To close the file, we utilise the object’s close() function.



Please Login to comment...

Similar Reads

Difference between Rich text and Plain text

What is Text.:- Collection of words or letters is called as text. This is a plain text-Geeks for Geeks This is a rich text- Geeks for Geeks It is clear from the above two types of text that what we are dealing with now lets see them one by one in detail and the difference between them. 1. PLAIN TEXT :Plain text is a text with no styles attached or

5 min read

Difference between Binary Tree and Binary Search Tree

Binary Tree Data Structure:A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right children. Binary Search Tree Data Structure (BST):A binary search tree is a hierarchical data structure where each node has at most two children, w

2 min read

Difference between File Descriptor and File Pointer

File descriptor is simply an index into the file descriptor table. For each process in our operating system, there is a process control block(PCB). PCB keeps track of the context of the process. So one of the fields within this is an array called file descriptor table. This array keeps track of all the resources that the process owns and can operat

3 min read

Difference between AI File Format and EPS File Format

AI stands for Adobe Illustrator and this file format was built to control the file size of high graphic images. This file format also works on a Postscript base. It was designed by Adobe corporation to manage vector drawings or artwork in an easier and more efficient manner. It uses the .ai file extension to save Adobe illustrator files. EPS stands

2 min read

Difference between Local File System (LFS) and Distributed File System (DFS)

In computers, file systems are essential components that help in managing how data will be stored and retrieved. It provides a structural way to store, organize and manage data on various storage devices such as USBs, hard drives, SSDs, etc. Different file systems have been created to meet the increasing demand for data processing and storage. The

4 min read

Difference between File Transfer Protocol (FTP) and Secure File Transfer Protocol (SFTP)

Data transfer is the most common task in network and system communications, and they involve transfer of files using two means i.e the File Transfer Protocol (FTP) and the Secure File Transfer Protocol (SFTP). FTP is a commonly applied protocol that enables files to be transferred through a network from one computer to another, but FTP is unsecure

5 min read

Difference Between Data Mining and Text Mining

Data Mining: Data mining is the process of finding patterns and extracting useful data from large data sets. It is used to convert raw data into useful data. Data mining can be extremely useful for improving the marketing strategies of a company as with the help of structured data we can study the data from different databases and then get more inn

3 min read

Difference between text() and html() method in jQuery

Text() Method: This method returns the text content of the selected elements. It overwrites the content of all the matches element while setting the content. Syntax: To return text content:$(selector).text()To set text content:$(selector).text(content)To set the text content using a function:$(selector).text(function(index, currentcontent)) html()

2 min read

Difference between Word Processor and Text Editor

1. Word Processor :Word Processor processes the words with pages and paragraphs. It is a processor that provides the basic editing, input, formatting, and output of the text with some additional features. It is a fully functioned desktop publishing program that produces error-free documents.2. Text Editor :It is a type of computer program which hel

3 min read

Difference between html() text() and val() methods in jQuery

In this article, we are going to discuss the differences between html(), text(), and val() methods and their usage. 1. jQuery html() method: The html() method is used to set or return the inner HTML of a selected element. It works similarly to innerHTML in normal JavaScript to set or get the content of the selected element. The above code tells the

4 min read

Difference between Text Mining and Natural Language Processing

Text Mining and Natural Language Processing (NLP) are both fields within the broader domain of computational linguistics, but they serve distinct purposes and employ different methodologies: Text MiningText Mining goal is to extract significant numeric indices from the text. Thus, make the facts contained in the textual content available to a range

3 min read

Difference Between text/xml and application/xml for Webservice Response

application/xmlThis is the recommended media type for XML data according to the IETF specifications [RFC 7303]. It signifies that the XML content might not be human-readable and could potentially contain processing instructions or other non-human-consumable elements. Syntax:Content-Type: application/xmlThis example demonstrates a web service respon

2 min read

Difference between General tree and Binary tree

General Tree: In the data structure, General tree is a tree in which each node can have either zero or many child nodes. It can not be empty. In general tree, there is no limitation on the degree of a node. The topmost node of a general tree is called the root node. There are many subtrees in a general tree. The subtree of a general tree is unorder

2 min read

Difference between Counting and Binary Semaphores

Prerequisite: Semaphores in Process Synchronization Overview A semaphore is an integer variable that is useful for solving a variety of synchronization problems. It imposes deliberate constraints that help programmers avoid errors. Moreover, it makes the solution more organized, making the programs portable and efficient. It can be accessed only th

5 min read

Difference between odd level and even level leaf sum in given Binary Tree

Given a Binary Tree, the task is to find the difference of the sum of leaf nodes at the odd level and even level of the given tree. Examples: Input: Output: -12Explanation: Following are the operations performed to get the result.odd_level_sum = 0, even_level_sum = 0Level 1: No leaf node, so odd_level_sum = 0Level 2: No leaf node, so even_level_sum

13 min read

Difference between Binary Semaphore and Mutex

Binary Semaphore and Mutex are both synchronization mechanisms used in concurrent programming to control access to shared resources and prevent race conditions. However, they have different characteristics and use cases Binary SemaphoreBinary semaphores are semaphores that can only assume the values 0 and 1. They are used for implementing the locks

3 min read

Difference between Binary tree and B-tree

B-Tree : B-Tree is known as a self-balancing tree as its nodes are sorted in the inorder traversal. Unlike the binary trees, in B-tree, a node can have more than two children. B-tree has a height of logM N (Where ‘M’ is the order of tree and N is the number of nodes). And the height is adjusts automatically at each update. In the B-tree data is sor

7 min read

Difference Between Decimal and Binary Number System

Decimal Number is defined by the number which has a whole number and the fractional part separated by a decimal point. While Binary Number is defined by a number which is expressed as in the base-2 numeral system. It is always written in the form of 0 and 1. In math, a system that is used to represent numbers in different forms is called number sys

7 min read

Difference between Binary Heap, Binomial Heap and Fibonacci Heap

Binary Heap:A Binary Heap is a Binary Tree with following properties. It’s a complete binary tree i.e., all levels are completely filled except possibly the last level and the last level has all keys as left as possible. This property of Binary Heap makes them suitable to be stored in an array.A Binary Heap is either Min Heap or Max Heap. In a Min

2 min read

Difference between Header file and Library

Header Files: The files that tell the compiler how to call some functionality (without knowing how the functionality actually works) are called header files. They contain the function prototypes. They also contain Data types and constants used with the libraries. We use #include to use these header files in programs. These files end with .h extensi

3 min read

Difference between YAML(.yml) and .properties file in Java SpringBoot

These are the files to have different configurations properties required to make the application up and run like to connect with the database what are the credentials, on which port the application will run, etc. YAML (.yml) File: YAML is a configuration language. Languages like Python, Ruby, Java heavily use it for configuring the various properti

3 min read

Difference between File and Folder

File: A File is defined as a set of related data or information that is being stored in secondary storage. A file is data file or a program file where former contains data and information in the form of alphanumeric, numeric or binary and latter containing the program code and can also be executed, is a program file. Example: Folder: It is used to

2 min read

Difference between Program and File

1. Program : Program, as name suggest, are simple executable files that contain set or collection of instructions used by computer to execute or complete particular tasks as well as produce results you want. 2. File : File, as name suggests, is basic concept in computer that is designed to store data or information also known as common storage unit

2 min read

Difference between Program and Executable File

1. Program : Program, as name suggest, are simply set of instructions developed by programmer that tell computer what to perform and consist of compiled code that run directly from operating system of computer. 2. Executable File : Executable File, as name suggests, are computer files that contain encoded sequence of instructions and is particular

2 min read

Difference Between FAT32, exFAT, and NTFS File System

When you write data to a storage medium whether it's a hard drive or an SSD or an SD card or a micro SD card or a USB flash drive you need to write the data in such a way that it can be found again. You can't just write it randomly on a drive and then expect to get it back one day when you need it. It needs to be organized and that organization is

5 min read

Difference between File System and DBMS

A file system and a DBMS are two kinds of data management systems that are used in different capacities and possess different characteristics. A File System is a way of organizing files into groups and folders and then storing them in a storage device. It provides the media that stores data as well as enables users to perform procedures such as rea

6 min read

Difference between SVG file and PNG

When it comes to choosing the right image format for your projects, understanding the difference between SVG and PNG files can make a big impact on the quality and performance of your designs. SVG (Scalable Vector Graphics) and PNG (Portable Network Graphics) are two popular image formats used in web design, digital art, and various other applicati

5 min read

Periodic Binary String With Minimum Period and a Given Binary String as Subsequence.

Periodic Binary String: A Binary string is called periodic if it can be written as a repetition of a binary string of smaller or same length. For example, 101010 is a periodic binary string with period 10 as we can get the string by repeatedly appending 10 to itself. In general, the string S with period P means, Si is equal to Si + P. Problem: Give

5 min read

Difference between Difference Engine and Analytical Engine

Introduction: The development of computing technology has a rich history, with many inventions and innovations leading to the creation of the modern computer. Two such machines, the Difference Engine and Analytical Engine, were created by the English mathematician and inventor Charles Babbage in the 19th century. While these machines share some sim

7 min read

Difference between Voltage Drop and Potential Difference

Voltage Drop is defined as the decrease in the electric potential along the path of current that is flowing in an electric circuit. Voltage drop can be assigned at each point in the electric circuit that is proportional to the electrical elevation. The amount of energy delivered per second to any component in the circuit is equal to the voltage dro

4 min read

Article Tags :

Practice Tags :

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

Difference Between C++ Text File and Binary File - GeeksforGeeks (5)

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `

${comment_text}

`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `

${suggest_val}

`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `

Thank You!

Your suggestions are valuable to us.

You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.

`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('

'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('

'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });

Difference Between C++ Text File and Binary File - GeeksforGeeks (2024)
Top Articles
6 Questions About the History of Money and Banking Answered
Aflac Supplemental Insurance
Sdn Md 2023-2024
Tabc On The Fly Final Exam Answers
What spices do Germans cook with?
Culver's Flavor Of The Day Wilson Nc
Undergraduate Programs | Webster Vienna
Cosentyx® 75 mg Injektionslösung in einer Fertigspritze - PatientenInfo-Service
Bc Hyundai Tupelo Ms
Superhot Unblocked Games
Valentina Gonzalez Leak
Craigslist Alabama Montgomery
Red Tomatoes Farmers Market Menu
I Wanna Dance with Somebody : séances à Paris et en Île-de-France - L'Officiel des spectacles
Spergo Net Worth 2022
Praew Phat
Craigslist Mt Pleasant Sc
SF bay area cars & trucks "chevrolet 50" - craigslist
/Www.usps.com/International/Passports.htm
Saritaprivate
Popular Chinese Restaurant in Rome Closing After 37 Years
Ups Print Store Near Me
St Clair County Mi Mugshots
R. Kelly Net Worth 2024: The King Of R&B's Rise And Fall
Jobs Hiring Near Me Part Time For 15 Year Olds
The Creator Showtimes Near R/C Gateway Theater 8
Hellraiser 3 Parents Guide
Page 2383 – Christianity Today
13301 South Orange Blossom Trail
Intel K vs KF vs F CPUs: What's the Difference?
ATM, 3813 N Woodlawn Blvd, Wichita, KS 67220, US - MapQuest
Busted! 29 New Arrests in Portsmouth, Ohio – 03/27/22 Scioto County Mugshots
Broken Gphone X Tarkov
Rogold Extension
Wake County Court Records | NorthCarolinaCourtRecords.us
Lehpiht Shop
Jay Gould co*ck
Flashscore.com Live Football Scores Livescore
That1Iggirl Mega
Weather Underground Bonita Springs
Cal Poly 2027 College Confidential
Invalleerkracht [Gratis] voorbeelden van sollicitatiebrieven & expert tips
Booknet.com Contract Marriage 2
Wordle Feb 27 Mashable
Port Huron Newspaper
Kenwood M-918DAB-H Heim-Audio-Mikrosystem DAB, DAB+, FM 10 W Bluetooth von expert Technomarkt
Jackerman Mothers Warmth Part 3
Meee Ruh
Is Chanel West Coast Pregnant Due Date
Research Tome Neltharus
The 5 Types of Intimacy Every Healthy Relationship Needs | All Points North
Noelleleyva Leaks
Latest Posts
Article information

Author: Nicola Considine CPA

Last Updated:

Views: 6035

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Nicola Considine CPA

Birthday: 1993-02-26

Address: 3809 Clinton Inlet, East Aleisha, UT 46318-2392

Phone: +2681424145499

Job: Government Technician

Hobby: Calligraphy, Lego building, Worldbuilding, Shooting, Bird watching, Shopping, Cooking

Introduction: My name is Nicola Considine CPA, I am a determined, witty, powerful, brainy, open, smiling, proud person who loves writing and wants to share my knowledge and understanding with you.