文件处理中给出奇怪值的流(指向文件结构的指针)
Stream (pointer to a file structure) in File handling giving strange values
我正在尝试使用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;
}
我试着用不同的模式来检查结果,以了解问题是怎么回事。当我调试它时,我得到的值(在读取模式下):
流=0x000000005c5c76f0{_ptr=0x0000000000000000_cnt=0 _base=0x000000000000000…}
我不知道它gib=ves坏指针,即使这样它也会进入循环的其他部分。为什么?
并且在写入模式下
流=0x0000000000000000{_ptr=??_cnt=??_base=??…}
所以转到循环的if部分。
此外,我的道路是正确的,我有足够的权限来完成我想要的任务。但为什么它会给出错误的指针呢?为什么我有这些奇怪的流值,我应该怎么做才能将缓冲区HtmlFileContents
的内容复制到z.txt
?有什么想法吗?
您正在以只读模式打开文件:fopen("C:\Users\sshekha\Desktop\z.txt","r");
。这里"r"
表示您只打算从文件中读取。为了能够写入内容(即fputs(...)
),请在写入模式下打开文件,如:fopen("C:\Users\sshekha\Desktop\z.txt","w")(or
;a"`如果要追加)。有关更多信息,请阅读fopen文档。
编辑:我看到你已经尝试了读写两种模式。你的代码只显示读取模式,因此我对只读问题的假设。让我再做一点调查,然后回来。
请在您的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
注意:该功能仅适用于"Pro"版本。
下面是一个工作示例:https://ideone.com/hVLgc4
如果文件是"只读"的,那么用写权限打开它应该会失败。
看看是不是这样,在窗口下:
- 右键单击文件
- 压力机特性
- 在底部,查看"只读"属性i是否标记有"v"(如果您希望写入文件,请取消选中它)
参考:
http://msdn.microsoft.com/en-us/library/aa365535(v=vs.85).aspx
关于如何从代码更改文件权限
- 如何在 C# 中映射双 C 结构指针?
- C++:映射结构中的结构指针
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- 类的静态结构指针声明在C++
- Windows 将标准的 C 文件结构注入到正在运行的进程中
- 在两个.cpp文件之间定义全局类/结构指针
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 用指向文件的指针存储数据结构
- 是否可以将无符号字符数组reinterpret_cast到仅包含C++中无符号字符成员的结构指针
- 如何读取/查询文件系统和文件结构
- 如何在地图中使用结构指针
- 结构指针在"新"调用上给出已分配的地址?
- 铸造结构指针指向C 的工会指针
- c++ 结构指针在初始化为 NULL 时无法读取内存
- 函数中的结构指针的地址为0x1
- C 用结构指针初始化结构
- C 结构指针铸成数组Interop C#
- 方法中不允许访问结构指针
- 如何打印出结构指针
- 文件处理中给出奇怪值的流(指向文件结构的指针)