Wednesday, July 8, 2020

File Handling In C++

File Handling In C++ How To Work With File handling in C++? Back Home Categories Online Courses Mock Interviews Webinars NEW Community Write for Us Categories Artificial Intelligence AI vs Machine Learning vs Deep LearningMachine Learning AlgorithmsArtificial Intelligence TutorialWhat is Deep LearningDeep Learning TutorialInstall TensorFlowDeep Learning with PythonBackpropagationTensorFlow TutorialConvolutional Neural Network TutorialVIEW ALL BI and Visualization What is TableauTableau TutorialTableau Interview QuestionsWhat is InformaticaInformatica Interview QuestionsPower BI TutorialPower BI Interview QuestionsOLTP vs OLAPQlikView TutorialAdvanced Excel Formulas TutorialVIEW ALL Big Data What is HadoopHadoop ArchitectureHadoop TutorialHadoop Interview QuestionsHadoop EcosystemData Science vs Big Data vs Data AnalyticsWhat is Big DataMapReduce TutorialPig TutorialSpark TutorialSpark Interview QuestionsBig Data TutorialHive TutorialVIEW ALL Blockchain Blockchain TutorialWhat is BlockchainHyperledger FabricWhat Is EthereumEthereum TutorialB lockchain ApplicationsSolidity TutorialBlockchain ProgrammingHow Blockchain WorksVIEW ALL Cloud Computing What is AWSAWS TutorialAWS CertificationAzure Interview QuestionsAzure TutorialWhat Is Cloud ComputingWhat Is SalesforceIoT TutorialSalesforce TutorialSalesforce Interview QuestionsVIEW ALL Cyber Security Cloud SecurityWhat is CryptographyNmap TutorialSQL Injection AttacksHow To Install Kali LinuxHow to become an Ethical Hacker?Footprinting in Ethical HackingNetwork Scanning for Ethical HackingARP SpoofingApplication SecurityVIEW ALL Data Science Python Pandas TutorialWhat is Machine LearningMachine Learning TutorialMachine Learning ProjectsMachine Learning Interview QuestionsWhat Is Data ScienceSAS TutorialR TutorialData Science ProjectsHow to become a data scientistData Science Interview QuestionsData Scientist SalaryVIEW ALL Data Warehousing and ETL What is Data WarehouseDimension Table in Data WarehousingData Warehousing Interview QuestionsData warehouse architectureTalend T utorialTalend ETL ToolTalend Interview QuestionsFact Table and its TypesInformatica TransformationsInformatica TutorialVIEW ALL Databases What is MySQLMySQL Data TypesSQL JoinsSQL Data TypesWhat is MongoDBMongoDB Interview QuestionsMySQL TutorialSQL Interview QuestionsSQL CommandsMySQL Interview QuestionsVIEW ALL DevOps What is DevOpsDevOps vs AgileDevOps ToolsDevOps TutorialHow To Become A DevOps EngineerDevOps Interview QuestionsWhat Is DockerDocker TutorialDocker Interview QuestionsWhat Is ChefWhat Is KubernetesKubernetes TutorialVIEW ALL Front End Web Development What is JavaScript â€" All You Need To Know About JavaScriptJavaScript TutorialJavaScript Interview QuestionsJavaScript FrameworksAngular TutorialAngular Interview QuestionsWhat is REST API?React TutorialReact vs AngularjQuery TutorialNode TutorialReact Interview QuestionsVIEW ALL Mobile Development Android TutorialAndroid Interview QuestionsAndroid ArchitectureAndroid SQLite DatabaseProgramming aria-current=page>Uncat egorizedHow To Work With File Handling... AWS Global Infrastructure C++ Programming Tutorial: The key you need to Master C++ What are the top 10 features of C++? Everything You Need To Know About Object Oriented Programming In C++ How To Work With File handling in C++? How To Implement Data Abstraction In C++ How To Implement Copy Constructor In C++? Data Hiding in C++: What is Encapsulation and Abstraction? How To Implement Constructor And Destructor In C++? What is a Storage Class in C++ and its types? How To Display Fibonacci Series In C++? How To Implement Pointers In C++? How To Implement This Pointer in C++? How To Implement Arrays In C++? How To Convert Integer To String In C++? How To Calculate String Length In C++? How To Convert Integer To String In C++? How To Implement Operator Overloading in c++? How To Implement Function Overloading And Overriding In C++? What are Maps in C++ and how to implement it? How To Implement Encapsulation In C++? How To Implement Exception Handling In C++? Goto Statement In C++ How To Implement Getline In C++? How To Implement Goto Statement In C++? How To Implement Sort function In C++? How To Implement Virtual Function in C++? How To Implement Inline Function in C++? How To Best Implement Type Conversion In C++? How To Work With File handling in C++? Last updated on May 07,2020 39.9K Views edureka Bookmark How To Work With File handling in C++? Whether it is the programming world or not, files are vital as they store data. This article discuss working of file handling in C++. Following pointers will be covered in the article,Opening a FileWriting to a FileReading from a FileClose a FileFile Handling In C++Files are used to store data in a storage device permanently. File handling provides a mechanism to store the output of a program in a file and to perform various operations on it.A stream is an abstraction that represents a device on which operations of in put and output are performed. A stream can be represented as a source or destination of characters of indefinite length depending on its usage.In C++ we have a set of file handling methods. These include ifstream, ofstream, and fstream. These classes are derived from fstrembase and from the corresponding iostream class. These classes, designed to manage the disk files, are declared in fstream and therefore we must include fstream and therefore we must include this file in any program that uses files.In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream.ofstream: This Stream class signifies the output file stream and is applied to create files for writing information to filesifstream: This Stream class signifies the input file stream and is applied for reading information from filesfstream: This Stream class can be used for both read and write from/to files.All the above three classes are derived from fstreambase and from the corresponding iostream class a nd they are designed specifically to manage disk files. C++ provides us with the following operations in File Handling:Creating a file: open()Reading data: read()Writing new data: write()Closing a file: close()Moving on with article on File Handling in C++Opening a FileGenerally, the first operation performed on an object of one of these classes is to associate it to a real file. This procedure is known to open a file.We can open a file using any one of the following methods: 1. First is bypassing the file name in constructor at the time of object creation. 2. Second is using the open() function.To open a file useopen() functionSyntaxvoid open(const char* file_name,ios::openmode mode);Here, the first argument of the open function defines the name and format of the file with the address of the file.The second argument represents the mode in which the file has to be opened. The following modes are used as per the requirements.ModesDescriptioninOpens the file to read(default for ifstre am)outOpens the file to write(default for ofstream)binaryOpens the file in binary modeappOpens the file and appends all the outputs at the endateOpens the file and moves the control to the end of the filetruncRemoves the data in the existing filenocreateOpens the file only if it already existsnoreplaceOpens the file only if it does not already existExample fstream new_file; new_file.open(newfile.txt, ios::out); In the above example, new_file is an object of type fstream, as we know fstream is a class so we need to create an object of this class to use its member functions. So we create new_file object and call open() function. Here we use out mode that allows us to open the file to write in it.Default Open Modes :ifstream ios::inofstream ios::outfstream ios::in | ios::outWe can combine the different modes using or symbol | .Exampleofstream new_file;new_file.open(new_file.txt, ios::out | ios::app );Here, input mode and append mode are combined which represents the file is opened for writing and appending the outputs at the end.As soon as the program terminates, the memory is erased and frees up the memory allocated and closes the files which are opened. But it is better to use the close() function to close the opened files after the use of the file.Using a stream insertion operator we can write information to a file and using stream extraction operator we can easily read information from a file.Example of opening/creating a file using the open() function #includeiostream #include fstream using namespace std; int main() { fstream new_file; new_file.open(new_file,ios::out); if(!new_file) { coutFile creation failed; } else { coutNew file created; new_file.close(); // Step 4: Closing file } return 0; } Output:Explanation In the above example we first create an object to class fstream and name it new_file. Then we apply the open() function on our new_file object. We give the name new_file to the new file we wish to create and we set the mode to out which allows us to write in our file. We use a if statement to find if the file already exists or not if it does exist then it will going to print File creation failed or it will gonna create a new file and print New file created.Moving on with article on File Handling in C++Writing to a FileExample: #include iostream #include fstream using namespace std; int main() { fstream new_file; new_file.open(new_file_write.txt,ios::out); if(!new_file) { coutFile creation failed; } else { coutNew file created; new_fileLearning File handling; //Writing to file new_file.close(); } return 0; } Output:ExplanationHere we first create a new file new_file_write using open() function since we wanted to send output to the file so, we use ios::out. As given in the program, information typed inside the quotes after Insertion Pointer got passed to the output file.Moving on with this article on File Handling in C++Reading from a FileExample #include iostream #include fstream using namespace std; int main() { fstream new_file; new_file.open(new_file_write.txt,ios::in); if(!new_file) coutNo such file; } else { char ch; while (!new_file.eof()) { new_file ch; cout ch; } new_file.close(); return 0; } Output:ExplanationIn this example, we read the file that generated id previous example i.e. new_file_write. To read a file we need to use in mode with syntax ios::in. In the above example, we print the content of the file using extraction operator . The output prints without any space because we use only one character at a time, we need to use getline() with a character array to print the whole line as it is.Moving on with this article on File Handling in C++Close a FileIt is simply done with the help of close() function.Syntax: File Pointer.close()Example #include iostream #include fstream using namespace std; int main() { fstream new_file; new_file.open(new_file.txt,ios::out); new_file.close(); return 0; } Output:The file gets closed.Thus we have come to an end of this article on File Handling in C++. If you wish to learn more, check out theJava Trainingby Edureka, a trusted online learning company. Edurekas Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate Spring.Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.Recommended blogs for you Why first 100 hours of learning is crucial? Read Article Vol. XX â€" Edureka Career Watch â€" 21st Sep 2019 Read Article Types of Software Testing : All You Need to Know About Testing Types Read Article Load Testing using JMeter : How to Measure Performance in CMD Read Article AIG Roadshow 2019 The Edureka Perspective Read Article What is Risk Analysis in Software Testing and how to perform it? Read Article #IndiaITRepublic â€" Top 10 Facts about Cognizant †" India Read Article How to Implement Odd Even Program in C Read Article #IndiaITRepublic Top 10 Facts about IBM India Read Article C# Tutorial: The Fundamentals you Need to Master C# Read Article What is Agile Testing? Know about Methods, Advantages and Principles Read Article What are Data Structures in C and How to use them? Read Article Vol. XXII â€" Edureka Career Watch â€" 9th Nov 2019 Read Article How To Implement Heap Sort In C? Read Article Vol. XI â€" Edureka Career Watch â€" 13th Apr. 2019 Read Article What is ITIL ®? One Stop Solution to IT Infrastructure Library Read Article Ethical Hacking Career: A Career Guideline For Ethical Hacker Read Article How To Implement Leap Year Program in C? Read Article #IndiaITRepublic â€" Top 10 Facts about TCS Read Article Edurekas PGP Learners Review Read Article Comments 0 Comments Trending Courses Python Certification Training for Data Scienc ...66k Enrolled LearnersWeekend/WeekdayLive Class Reviews 5 (26200)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.