【问题标题】:C++ fstream is_open() function always returns falseC++ fstream is_open() 函数总是返回 false
【发布时间】:2014-11-22 09:33:34
【问题描述】:

我尝试使用 open() 打开与源文件位于同一目录中的 html 文件。但是我不知道为什么 is_open() 在我的程序中总是返回 false ...... 这是我的部分源代码

readHTML.cpp中打开html文件的函数之一

 #include "web.h"
         ...
void extractAllAnchorTags(const char* webAddress, char**& anchorTags, int& numOfAnchorTags)
    {
        ifstream myfile;
        char line[256];
        char content[2048] = "";

        numOfAnchorTags = 0;
        myfile.open(webAddress);
        cout<< myfile.is_open()<<endl;
        if (myfile.is_open())
        {......}
    }

头文件,web.h

#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

struct WebNode
{
    char* webAddress; 
    char* anchorText;
    WebNode** hyperlink;
    int numOfHyperlinks;
};

void extractAllAnchorTags(const char* webAddress, char**& anchorTags, int& numOfAnchorTags);

另一个cpp文件,调用F.cpp

#include "web.h"
........
WebNode* createWeb(const char* webAddress, const char* anchorText, int height)
{
    if(height != 0){
       WebNode* webNode = new WebNode;
       char** anchorTags;
       int numOfAnchorTags;
       strcpy(webNode->webAddress,webAddress);
       strcpy(webNode->anchorText,anchorText);
       extractAllAnchorTags(webAddress,anchorTags,numOfAnchorTags);
        \*.........................*\
 }
 .......

main.cpp

#include "web.h"

     int main(){
        .............
        cin >> filename;  // index.html   would be input during running.
        Page = createWeb(filename, anchorText, max_height);
        .............
      }

我的 main.cpp 只需调用一次 createWeb 但是我得到的 myfile.is_open() 总是返回 false,因为它在我的 Eclipse 控制台中打印出 0 ... 我不知道为什么我什至尝试将我的参数目录重置为我的工作区 或者我将我的 html 文件放在调试文件夹中.. 它仍然返回 false。

【问题讨论】:

  • 哪个操作系统?
  • 我使用的是 Windows 7 64 位

标签: c++ fstream


【解决方案1】:

你写入未初始化的指针:

struct WebNode
{
    char* webAddress; 
    char* anchorText;
    WebNode** hyperlink;
    int numOfHyperlinks;
};

// ...

WebNode* webNode = new WebNode;
strcpy(webNode->webAddress,webAddress);

指针webNode-&gt;webAddress 目前没有指向任何地方。要解决此问题,请将其类型从 char * 更改为 std::string,并使用字符串赋值来复制字符串内容。

您复制到未初始化的指针会导致未定义的行为,这可能会导致内存损坏等,因此您的程序的其余部分似乎会失败。

您还应该重新设计extractAllAnchorTags 以不使用指针。

【讨论】:

  • 感谢您对我的启发。我尝试交换我的代码顺序以避免这种内存损坏。谢谢。你节省了我很多时间
【解决方案2】:

ifstream 类无法打开网站。它只打开文件。您需要使用 CURL 等库。

【讨论】:

  • 如果我要读取html文件的源代码,因为我需要读取html源代码中的内容?我尝试创建另一个程序,它只是简单地打开 html 文件,它对我返回 true...我不知道为什么会发生这种情况..
  • 我假设变量 webAddress 是一个 URL。我说的对吗?
  • webAddress 为 html 名称,例如 index.html
  • 您打开的是文件还是 URL?
  • 打开一个文件,我把index.html和源代码放在同一个文件夹下。然后我使用 webAddress 作为将“index.html”存储为字符串数组的变量。然后我应该打开文件以获取该 index.html 文件的源代码的一些信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多