Search code examples
c++windowswinapifile-ioevent-log

How to print data from stringstream to a file?


I have opened a file using CreateFile fn and tried to print data into the file. Since the data includes some print statements like

wprintf(L"Channel %s was not found.\n", pwsPath);

The declaration for DATA and pwsPath

#include <iostream>
#include <sstream>

using namespace std;
string data;
LPWSTR pwsPath = L"Channel1";

I tried to use stringstream to get the data and convert it to a LPCVOID to use the WriteFile fn as shown

hFile1 = CreateFile(L"MyFile.txt",                // name of the write
                   GENERIC_WRITE,          // open for writing
                   0,                      // do not share
                   NULL,                   // default security
                   CREATE_ALWAYS,             // create new file only
                   FILE_ATTRIBUTE_NORMAL,  // normal file
                   NULL); 

std::stringstream ss;
ss << "Channel" << pwsPath << "was not found.";

ss >> data;
cout << data; // data contains value only till the first space i.e Channel093902
cin>>data;



         bErrorFlag = WriteFile( 
                hFile1,           // open file handle
                data.c_str(),      // start of data to write
                dwBytesToWrite,  // number of bytes to write
                &dwBytesWritten, // number of bytes that were written
                NULL); 

Is it possible for variable data to include spaces from the stringstream ?? OR Is there any other way other than stringstream to get the data from such print statements and write to the file as such?


Solution

  • The >> operator will deliver the next 'word' in the stream into the string object you have given it. It breaks at the first white space as you have found. There are a couple of ways to achieve what you want. The most conformant is to open the output file as an ofstream:

    #include <iostream>
    #include <sstream>
    #include <fstream>
    
    using namespace std;
    
    
    int main()
    {
        std::string pwsPath { "[enter path here]" };
        std::stringstream ss;
        ss << "Channel " << pwsPath << " was not found.";   
    
        std::ofstream outFile("myFile.txt");
        outFile << ss.rdbuf();
        outFile.close();
    
        std::ifstream inFile("myFile.txt");
        cout << inFile.rdbuf();
    
        return 0;
    }
    

    otherwise you can get the internal string from the ostringstream:

    std::string myData = ss.str();
    size_t dataLength = myData.length();
    DWORD dwBytesWritten = 0;
    BOOL bErrorFlag = WriteFile( 
                    hFile1,           // open file handle
                    myData.data(),      // start of data to write
                    DWORD(dataLength),  // number of bytes to write
                    &dwBytesWritten, // number of bytes that were written
                    NULL);