C++ fstream is_open() function always returns false

末鹿安然 提交于 2019-12-13 04:59:24

问题


I have tried to use open() to open html file in the same directory as the source file. However I dont know why is_open() always return false in my program.... Here is part of my source code

one of the functions to open html file in readHTML.cpp

 #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())
        {......}
    }

header file, 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);

another cpp file, callF.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);
        .............
      }

my main.cpp just call createWeb once However what i get that myfile.is_open() always returns false since it prints out 0 in my console of eclipse... I have no idea why even I try to reset my argument directory to my workspace or I put my html file inside debug folder .. it still returns false.


回答1:


You write to uninitialized pointers:

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

// ...

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

The pointer webNode->webAddress does not currently point anywhere. To fix this, change its type from char * to std::string, and use string assignment to copy the string contents.

Your copying to uninitialized pointer causes undefined behaviour which may result in memory corruption and so on, so the rest of your program appears to fail.

Also you should redesign extractAllAnchorTags to not use pointers.




回答2:


The class ifstream cannot open web sites. It only opens files. You need to use a library such as CURL.



来源:https://stackoverflow.com/questions/27075930/c-fstream-is-open-function-always-returns-false

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!