我尝试使用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文件,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);
.............
}
然而,我的main.cpp只调用了一次createWeb,createWeb()总是返回false,因为它在eclipse的控制台中打印出0.我不知道为什么我甚至试图将我的参数目录重置到我的工作区,或者我把我的html文件放在调试文件夹中。它仍然返回假。
发布于 2014-11-22 10:22:50
写入未初始化的指针:
struct WebNode
{
char* webAddress;
char* anchorText;
WebNode** hyperlink;
int numOfHyperlinks;
};
// ...
WebNode* webNode = new WebNode;
strcpy(webNode->webAddress,webAddress);
指针webNode->webAddress
当前没有指向任何位置。若要解决此问题,请将其类型从char *
更改为std::string
,并使用字符串赋值复制字符串内容。
对未初始化指针的复制会导致未定义的行为,这可能导致内存损坏等,因此程序的其余部分似乎失败。
此外,您还应该重新设计extractAllAnchorTags
,使其不使用指针。
发布于 2014-11-22 09:43:31
类ifstream
不能打开网站。它只打开文件。您需要使用库,如CURL。
https://stackoverflow.com/questions/27075930
复制相似问题