我使用 CreateFile fn 打开了一个文件,并尝试将数据打印到文件中。由于数据包含一些打印语句,例如
wprintf(L"找不到 channel %s。\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);
变量 data 是否可以包含字符串流中的空格?? 或者 除了 stringstream 之外,还有其他方法可以从此类打印语句中获取数据并写入文件吗?
最佳答案
>> 运算符会将流中的下一个“单词”传送到您提供的字符串对象中。正如您所发现的,它在第一个空白处中断。有几种方法可以实现您想要的。最符合要求的是将输出文件作为 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);
关于c++ - 如何将字符串流中的数据打印到文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23731785/