Search code examples
c++fstream

C++ fstream is_open() function always returns false


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.


Solution

  • 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.