首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C++ fstream is_open()函数总是返回false

C++ fstream is_open()函数总是返回false
EN

Stack Overflow用户
提问于 2014-11-22 09:33:34
回答 2查看 3.2K关注 0票数 0

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

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

代码语言:javascript
运行
复制
 #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

代码语言:javascript
运行
复制
#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文件,callF.cpp

代码语言:javascript
运行
复制
#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

代码语言:javascript
运行
复制
#include "web.h"

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

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-11-22 10:22:50

写入未初始化的指针:

代码语言:javascript
运行
复制
struct WebNode
{
    char* webAddress; 
    char* anchorText;
    WebNode** hyperlink;
    int numOfHyperlinks;
};

// ...

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

指针webNode->webAddress当前没有指向任何位置。若要解决此问题,请将其类型从char *更改为std::string,并使用字符串赋值复制字符串内容。

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

此外,您还应该重新设计extractAllAnchorTags,使其不使用指针。

票数 0
EN

Stack Overflow用户

发布于 2014-11-22 09:43:31

ifstream不能打开网站。它只打开文件。您需要使用库,如CURL。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27075930

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档