CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11

Thread: File I/O

Threaded View

  1. #1
    Join Date
    Apr 2022
    Posts
    11

    File I/O

    I am trying to read a file into buffer as vector, and write it to another file. It reads the content, but doesn't seem to write. What is the mistake and how to correct ?

    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>
    /*
     * It will iterate through all the lines in file and
     * put them in given vector
     */
    bool getFileContent(std::string infileName, std::string outfileName, std::vector<std::string>& vecOfStrs)
    {
        // Open the File to read the content into buffer
        std::ifstream in(infileName.c_str());
    
        // Check if object is valid
        if (!in)
        {
            std::cerr << "Cannot open the File : " << infileName << std::endl;
            return false;
        }
    
        std::string str;
        // Read the next line from File untill it reaches the end.
        while (std::getline(in, str))
        {
            // Line contains string of length > 0 then save it in vector
            if (str.size() > 0)
                vecOfStrs.push_back(str);
        }
    
        //Open the file to output the read buffer
        std::ofstream out(outfileName.c_str());
         
        if (!out) {
            std::cerr << "Write operation failed.";
            return false;
        }
        /*while (in >> std::noskipws >> ch) {
            out << ch;
        }*/
    
        //Iterate through the vector, and write it to the file 
        for (std::string& row : vecOfStrs) {
            out << row << std::endl;
        }
        out.close();
        in.close();
        return true;
    }
    
    int main()
    {
        std::vector<std::string> vecOfStr;
        // Get the contents of file in a vector
        bool result = getFileContent("sample.txt", 
            "output.txt",vecOfStr);
        if (result)
        {
            // Print the vector contents
            std::cout << "Success! File read and write done";
        }
    }
    Last edited by perto1; April 10th, 2022 at 07:53 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured