如何将数据从stringstream打印到文件?

时间:2014-05-19 07:13:12

标签: c++ windows winapi file-io event-log

我使用 CreateFile fn打开了一个文件,并尝试将数据打印到文件中。由于数据包括一些打印语句,如

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

DATA和pwsPath的声明

#include <iostream>
#include <sstream>

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

我尝试使用stringstream获取数据并将其转换为LPCVOID以使用 WriteFile fn,如图所示

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); 

变量数据是否有可能包含来自stringstream的空格? 要么 除了stringstream之外还有其他方法可以从这样的print语句中获取数据并写入文件吗?

2 个答案:

答案 0 :(得分:2)

除非你有充分的理由使用CreateFile和WriteFile,否则请考虑一直使用std对象。

您的代码可能如下所示:

#include <iostream>
#include <fstream> // add this

#include <sstream> // remove this unless used elsewhere

// your pwsPath
std::wstring path{ L"Channel1" };

std::wofstream out{ L"MyFile.txt", std::wofstream::trunc };

// skip the stringstream completely
out << "Channel " << path << " was not found."

答案 1 :(得分:1)

&gt;&gt; operator将把流中的下一个“单词”传递给你给它的字符串对象。它在您发现的第一个空白处打破了。有几种方法可以达到你想要的效果。最符合的是打开输出文件作为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;
}

否则你可以从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);