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

Thread: File I/O

  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.

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,279

    Re: File I/O

    Did you debug this code?
    How did you check that "it reads the content"? Did you check the content of the vecOfStrs after the read had finished?
    Did you check whether this operation
    Code:
        for (std::string& row : vecOfStrs) {
            out << row << std::endl;
        }
    succeeded?
    Victor Nijegorodov

  3. #3
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,664

    Re: File I/O

    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>
    
    bool getFileContent(const std::string& infileName, const std::string& outfileName, std::vector<std::string>& vecOfStrs) {
        std::ifstream in(infileName);
    
        if (!in)
            return (std::cerr << "Cannot open the File : " << infileName << '\n'), false;
    
        for (std::string str; std::getline(in, str); )
            if (!str.empty())
                vecOfStrs.push_back(str);
    
        std::ofstream out(outfileName);
    
        if (!out)
            return (std::cerr << "Write operation failed.\n"), false;
    
        for (const auto& row : vecOfStrs)
            out << row << '\n';
    
        return true;
    }
    
    int main() {
        std::vector<std::string> vecOfStr;
    
        if (getFileContent("test1.txt", "output.txt", vecOfStr)) {
            for (const auto& s : vecOfStr)
                std::cout << s << '\n';
    
            std::cout << "\nSuccess! File read and write done";
        }
    }
    copies non-blank lines between text files OK.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.3.5)

  4. #4
    Join Date
    Apr 2022
    Posts
    11

    Re: File I/O

    I want to modify the code as different functions. Any suggestions what improvements to make:

    Code:
    std::string getFileContent(const std::string & infileName)//Should it return vecOfStrs, change it to string type
    {
        // Open the File to read the content into buffer
        std::vector<std::string> vecOfStrs;
        std::ifstream in(infileName.c_str());
    
        // Check if object is valid
        if (!in)
        {
            throw (std::runtime_error("Cannot open the File : " ));
    
        }
    
        std::string str;
    
        // Read the next line from File untill it reaches the end.
    
        std::getline(in, str);
    
        while (std::getline(in, str))
        {
            // Line contains string of length > 0 then save it in vector
            if (str.size() > 0)
                vecOfStrs.push_back(str+"\n");
        }
        size_t bytes_read = sizeof(vecOfStrs[0]) * vecOfStrs.size();
        /*for (const auto& str : vecOfStrs)
            std::cout << str << '\n';*/
    
    
    
        in.close();
        return  vecOfStrs;//This is not valid operation
       
    
    }

    Code:
    void writeFileContent(std::string outfileName){
        std::vector<std::string> vecOfStrs;
        std::string str;
        //Open the file to output the read buffer
        std::ofstream out(outfileName.c_str());
    
        if (!out)
        {
            throw (std::runtime_error("Cannot open the File : " ));
            //return false;//Replace with something ?
        }
    
        std::string result = getFileContent("sample.txt");//Test with binary as well
    
        if(result.size()==bytes_read)
        {
            for (const auto& row : vecOfStrs)
                out << row << '\n';
        }
        out.close();
    
        //return str.size();
    
    }//Close of the write function

  5. #5
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,664

    Re: File I/O

    What are you trying to accomplish?? Based upon the provided code:

    Code:
    #include <fstream>
    #include <iostream>
    #include <string>
    #include <vector>
    #include <exception>
    
    auto getFileContent(const std::string& infileName) {
    	std::ifstream in(infileName);
    
    	if (!in)
    		throw (std::runtime_error("Cannot open the File : "));
    
    	std::vector<std::string> vecOfStrs;
    
    	for (std::string str; std::getline(in, str); )
    		if (!str.empty())
    			vecOfStrs.push_back(str);
    
    	return vecOfStrs;
    }
    
    void writeFileContent(const std::string& outfileName) {
    	std::ofstream out(outfileName);
    
    	if (!out)
    		throw (std::runtime_error("Cannot open the File : "));
    
    	for (const auto& row : getFileContent("sample.txt"))
    		out << row << '\n';
    }
    
    int main() {
    	writeFileContent("out.txt");
    }
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.3.5)

  6. #6
    Join Date
    Apr 2022
    Posts
    11

    Re: File I/O

    Use for client server communication

  7. #7
    Join Date
    Apr 2022
    Posts
    11

    Re: File I/O

    If I have size of vector as
    Code:
     size_t bytes_read = sizeof(vecOfStrs[0]) * vecOfStrs.size();
    in the getFileContent(), how do i call it in the writeFileContent and make comparison if they are equal.

    In the writeFileContent, i can have
    Code:
      size_t bytes_written = out.tellp()
    . Now I want to compare if bytes_read ==bytes_written

  8. #8
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,664

    Re: File I/O

    As vecOfStrs is std::vector<std::string>, the number of chars used for each entry is not the same. Also the data is stored in dynamic memory so sizeof() doesn't give the number of bytes stored for an entry. Hence this method won't give the number of bytes used to store the data.

    Also, as you are reading/writing a text file the size of the data stored in the vector doesn't take into account the line terminating chars. On Windows, these are 2 (\n\r) but on other systems this is just one char (\n) - even though you use \n in both cases to terminate a line when writing (getline() automatically deals with both cases).

    You can do something like this, but this is OS specific (this code is for Windows):

    Code:
    #include <fstream>
    #include <iostream>
    #include <string>
    #include <vector>
    #include <exception>
    
    auto getFileContent(const std::string& infileName, size_t& bytes) {
    	std::ifstream in(infileName);
    
    	if (!in)
    		throw (std::runtime_error("Cannot open the File : "));
    
    	std::vector<std::string> vecOfStrs;
    
    	bytes = 0;
    	for (std::string str; std::getline(in, str); )
    		if (!str.empty()) {
    			vecOfStrs.push_back(str);
    			bytes += str.size() + 2;	// Assumes 2 bytes for end of line marker
    		}
    
    	return vecOfStrs;
    }
    
    void writeFileContent(const std::string& outfileName) {
    	std::ofstream out(outfileName);
    
    	if (!out)
    		throw (std::runtime_error("Cannot open the File : "));
    
    	size_t bytes {};
    
    	for (const auto& row : getFileContent("sample.txt", bytes))
    		out << row << '\n';
    
    	std::cout << "Read "<< bytes << ", wrote " << out.tellp() << '\n';
    }
    
    int main() {
    	writeFileContent("out.txt");
    }
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.3.5)

  9. #9
    Join Date
    Apr 2022
    Posts
    11

    Re: File I/O

    Is the bytes in writeFileContent
    Code:
     size_t bytes {};
    accessing the getFileContent()'s bytes ? For me it shows 0 bytes read

  10. #10
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,279

    Re: File I/O

    Quote Originally Posted by perto1 View Post
    Is the bytes in writeFileContent
    Code:
     size_t bytes {};
    accessing the getFileContent()'s bytes ? For me it shows 0 bytes read
    Debug your code to see/understand what happens inside your getFileContent() function!
    Victor Nijegorodov

  11. #11
    Join Date
    Apr 2022
    Posts
    11

    Re: File I/O

    Once size_t& bytes has been passed as parameter in function, we just call it with the name later instead of defining it again as
    Code:
    size_t bytes_read
    . My finding.

    Thanks.

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