文件处理中的流(指向文件结构的指针)给出奇怪的值

时间:2013-07-25 07:15:32

标签: c++ filestream fopen file-handling fputs

我正在尝试使用visual c ++将缓冲区输出到文件。 我的代码是 -

FILE *stream;

stream=fopen("C:\\Users\\sshekha\\Desktop\\z.txt","r");

//I also tried with "w" mode
//the differencein behavious on executing these two is that when it is in read mode it 
//executes the else condition in the code below whereas in "w" mode it executes the "if"
// condition, 
//moreover even if i change the path it don't execute the "else" condition-that means this path
//is effective to the code. and  the another surprising thing is when i open the file manually
// and then run the code with "r" mode it still executes the "else" part (which it shouldn't
// because the file is already open.) 

if( stream == 0 )
{
    MessageBox(m_hwndPreview,L" the file is not opened ",L"BTN WND",MB_ICONINFORMATION);
}
else
{
    MessageBox(m_hwndPreview,L" the file is opened ",L"BTN WND",MB_ICONINFORMATION);
    int check=fputs (HtmlFileContents,stream);
    fclose(stream);
    return 0;
}

我尝试使用不同的模式检查结果,以便了解探测的内容。当我调试它时,我得到(在读模式下)的值:

  

stream = 0x000000005c5c76f0 {_ptr = 0x0000000000000000 _cnt = 0 _base = 0x0000000000000000 ...}

我不知道gib = ves坏指针,即使那时它也会转到其他部分循环。为什么?

并处于写入模式

  

stream = 0x0000000000000000 {_ptr = ??? _cnt = ??? _base = ??? ...}

所以转到循环的if部分。

此外,我的路径是正确的,我有足够的许可来完成我希望的任务。但为什么它会给坏指针?为什么我有这些奇怪的流值,我该怎么做才能将缓冲区HtmlFileContents的内容复制到z.txt?有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您以只读模式打开文件:fopen("C:\\Users\\sshekha\\Desktop\\z.txt","r");。这里"r"表示您只打算从文件中读取。为了能够写入内容(即fputs(...)),请在写入模式下打开文件,如下所示:fopen(“C:\ Users \ sshekha \ Desktop \ z.txt”,“w”)(or “a”`如果你想追加)。有关详细信息,请read fopen documentation

编辑:我看到你尝试了读写模式。你的代码只显示读模式,因此我对只读问题的假设。让我做一些研究并回来。

请在if声明中填写以下代码:

perror("The following error occurred:");

如果您没有控制台,请使用它来存储错误字符串:

char* errorCause = strerror(errno); MessageBoxA(m_hwndPreview, errorCause, "BTN WND", MB_ICONINFORMATION);

让我们知道您所看到的原因。

编辑2:既然您已经提到过您使用的是Visual Studio 2010,那么您是否正在运行它?此stackoverflow答案显示VS2010在调试应用程序时有不同的选项; https://stackoverflow.com/a/3704942/210634

注意:该功能仅适用于'专业版'。

以下是一个有效的例子:https://ideone.com/hVLgc4

答案 1 :(得分:0)

如果文件是“只读”,则使用写入权限打开该文件将失败。

在Windows下查看是否是这种情况:

  • 右键单击文件
  • 按属性
  • 在底部,查看“只读”属性是否标有“v” (如果你想写文件,请取消选中)

参考:

http://msdn.microsoft.com/en-us/library/aa365535(v=vs.85).aspx

如何更改代码中的文件权限