【问题标题】:Stream (pointer to a file structure) in File handling giving strange values文件处理中的流(指向文件结构的指针)给出奇怪的值
【发布时间】:2013-07-25 16:07:34
【问题描述】:

我正在尝试使用 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=0x0000000000000000 ...}

我不知道它 gib=ves 错误的指针,即使这样它也会转到循环的 else 部分。为什么?

并处于写入模式

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

所以转到循环的 if 部分。

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

【问题讨论】:

  • 您正在以只读模式打开文件并对其进行写入。那是你的问题。
  • 不,我这样做只是为了向您解释不同模式下的行为(w/r)。在“w”模式下,它进入 if 循环(我的意思是流返回零),而在“r”模式下,它进入第二个循环,这意味着流有一些内容,但它有一些 你可以在上面看到。为什么这样做?以及为什么当模式为“w”时控件不进入其他条件??
  • "r" 绝对是错误的模式。你试过“w+”吗?
  • Vite 我已经完成了..当我这样做时,控件进入“if”条件。我的意思是在这种情况下流返回零。

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


【解决方案1】:

您正在以只读模式打开文件: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

【讨论】:

  • 我认为您没有正确阅读问题,请参阅“而在“w”模式下它执行“if”条件”。
  • @ShekharSinghSHEKHAWAT:是的。我的“编辑”部分有这部分。
【解决方案2】:

如果文件是“只读”的,用写权限打开它应该会失败。

看看是不是这样,windows下:

  • 右键文件
  • 新闻属性
  • 在底部,查看“只读”属性是否标有“v” (如果您想写入文件,请取消选中它)

参考:

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

关于如何从您的代码更改文件权限

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 2017-03-22
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多