C++ 写入文本文件时出现奇怪的字符

C++ Strange characters appear when writing to text file

我有一个程序可以在每次用相机拍摄照片时写出帧数和当前系统时间:

SYSTEMTIME st;
GetSystemTime(&st);
lStr.Format( _T("%d   %d.%d.%d.%d\r\n"),GetFrames() ,st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);

std::wfstream myfile;  
myfile.open("test.txt", std::ios::out | std::ios::in | std::ios::app );
    if (myfile.is_open())
            {
            myfile.write((LPCTSTR)lStr, lStr.GetLength()*sizeof(TCHAR));
            myfile.close();
            }
        else {lStr.Format( _T("open file failed: %d"), WSAGetLastError());
        }

程序输出的文本文件似乎正确地写入了数据,但我得到了每行开头不应该出现的空格和字符。该网站似乎没有正确格式化空格,所以我将 post 一张图片,这就是文本文件的样子。除了零之外,该文件有时还会显示项目符号点。

如您所见,第一行很好,但我写入文本文件的时间越长,情况似乎越糟。该程序每秒大约写入文件 10 次。我是 C++ 的新手,我不确定是什么原因造成的。我试图寻找与此类似的其他问题,但他们似乎没有我正在寻找的解决方案。任何帮助将不胜感激。

当您使用 std::wfstream::write (basic_ostream) 时,它会占用您的字符串的大小。您再次将该大小乘以 * sizeof(TCHAR)。删除这个额外的乘法应该可以简单地解决你的问题。


尽管如果您遇到任何其他问题(例如第三方库 returns 空格太多),您总是可以 trim 字符串。

一个基本的例子:

template<class TString>
static inline TString &trim_left(TString &s)
{
    s.erase(std::begin(s), std::find_if(std::begin(s), std::end(s), std::not1(std::ptr_fun<int, int>(std::isspace))));
    return s;
}

template<class TString>
static inline TString &trim_right(TString &s)
{
    s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), std::end(s));
    return s;
}

template<class TString>
static inline TString &trim(TString &s)
{
    return trim_left(trim_right(s));
}

解决方案分为两部分:

lStr.Format( _T("%d   %d.%d.%d.%d\r\n"),GetFrames() ,st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);

应该是

lStr.Format( _T("%lu   %d.%d.%d.%d\n"),GetFrames() ,st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);

As GetFrames() returns DWORDunsigned long 并且您将文件写入文本,因此 \n 转换为 \r\n如果需要,取决于操作系统。

另一部分是wfstream::write的第二个参数是字符数而不是字节数所以

myfile.write((LPCTSTR)lStr, lStr.GetLength()*sizeof(TCHAR));

应该是

myfile.write((LPCTSTR)lStr, lStr.GetLength());