🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

File I/O Functions

C++ File I/O Operations

C++ File I/O Operations

Writing to a File (Output):

  1. Open a File:
  2.     #include <fstream>
    
        int main() {
            std::ofstream outputFile("example.txt");
    
            // Write data to the file
    
            outputFile.close(); // Close the file when done
            return 0;
        }
        
  3. Write Data to the File:
  4.     outputFile << "Hello, File I/O!" << std::endl;
        
  5. Append Data to a File:
  6.     std::ofstream outputFile("example.txt", std::ios::app);
        

Reading from a File (Input):

  1. Open a File for Reading:
  2.     #include <fstream>
    
        int main() {
            std::ifstream inputFile("example.txt");
    
            // Read data from the file
    
            inputFile.close(); // Close the file when done
            return 0;
        }
        
  3. Read Data from the File:
  4.     std::string word;
        inputFile >> word; // Read a word
    
        std::string line;
        std::getline(inputFile, line); // Read a line
        
  5. Check for End-of-File (EOF):
  6.     while (!inputFile.eof()) {
            // Read data from the file
        }
        
  7. Check if File is Open:
  8.     if (inputFile.is_open()) {
            // File operations
        } else {
            std::cerr << "Unable to open the file." << std::endl;
        }
        

Error Handling:

  1. Exception Handling:
  2.     try {
            // File operations
        } catch (const std::exception& e) {
            std::cerr << "Error: " << e.what() << std::endl;
        }
        

These examples cover the basic operations for file I/O in C++. Depending on your specific requirements, you may need to explore more advanced features, such as binary file I/O, random access, and handling different file formats. Always remember to handle errors appropriately to ensure robust file handling.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.