在文本文件中写入值,获取运行时检查错误 我在Windows 7中编程,使用MS Visual C++ 2010。

在文本文件中写入值,获取运行时检查错误 我在Windows 7中编程,使用MS Visual C++ 2010。,c,C,我使用的API允许我访问以下错误代码: // iResult holds the error codes lResult.GetCodeString() 我需要在文本文件中编写此代码。下面是我如何进行的: char buff[10]; strcpy (buff, lResult.GetCodeString()); pFile_display = fopen ("D:\\ABCD\\myfile_display.txt","a+"); fputs("\nthe error vlaue ret

我使用的API允许我访问以下错误代码:

// iResult holds the error codes
lResult.GetCodeString()
我需要在文本文件中编写此代码。下面是我如何进行的:

char buff[10];

strcpy (buff, lResult.GetCodeString());

pFile_display = fopen ("D:\\ABCD\\myfile_display.txt","a+");
fputs("\nthe error vlaue returned is ", pFile_display ); 
fwrite (buff, sizeof(char), sizeof(buff), pFile_display);

有没有更好的方法可以做到这一点,因为我得到了运行时检查错误,我怀疑我在这里做错了什么

是的,这是一种不好的做法

  • 您不知道错误消息的长度,但您只保留了10个字符的空间。这并不多
  • 在将消息写入文件之前,完全不需要将其复制到第二个缓冲区
  • 使用
    sizeof
    计算字符串长度的操作被中断
  • 当数据是字符串时,无需使用用于写入二进制数据的低级函数(即,
    fwrite()
  • 只要做:

    fprintf(pFile_display, "The error is '%s'\n", lResult.GetCodeString());
    
    顺便说一句,这表明
    GetCodeString()
    的返回值可能不是C字符串。你应该做:

    fprintf(pFile_display, "The error is '%s'\n", lResult.GetCodeString().GetAscii());
    

    以获得正确的格式。当然,您应该会因此收到编译器警告。

    谢谢。顺便问一下,我们所说的“坏了”是什么意思@user3891236我的意思是“不工作”、“不正确”、“不工作”等等。不起作用的代码通常被认为是坏代码;错误返回为“°ôZ\õZP!”!ôZÊôZlist太长。这里怎么了?@user3891236没有
    sprintf()
    。您应该使用
    fprintf()
    直接打印到文件中。也许
    GetCodeString()
    返回的字符串毕竟不是有效的C字符串?对不起,我只是指fprintf。