0

I am working on a text processor that takes in text from a file and inserts it into a Graph data structure. I made the Graph, but I am having trouble with the text processor. Whenever I execute the code, it says I am unable to open the file. I made sure that the text file was in the same directory when I executed the code. Here is the code for the GraphTextProcessor class:

#include <fstream>
#include <cstring>
#include <string>
#include "Graph.h"

class GraphTextProcessor {
    private:
        Graph* m_data;

    public:
        GraphTextProcessor();
        Graph* process(std::string filename);
};

GraphTextProcessor::GraphTextProcessor() {
}

Graph* GraphTextProcessor::process(std::string filename) {
    //process text file and insert into graph here

    std::string word;

    //opens file in read mode
    std::ifstream readFile;
    readFile.open(filename.c_str(), std::ios::in);

    if (readFile.is_open()) { //Not opening
        while (readFile >> word) {
            std::cout << word << std::endl;
        }
        // Closes open text file
        readFile.close();
    }
    else {
        std::cout << "Unable to open text file." << std::endl;
    }

    return NULL;
}

I am just trying to read from a file first before I actually try writing to the Graph. Here is the code that I am running in Main:

#include <iostream>
#include <string>
#include "GraphTextProcessor.h"

int main() {
    GraphTextProcessor *gp = new GraphTextProcessor();
    gp->process("hello.txt");
}

It prints "Unable to open text file". Any suggestions?

Kyle A
  • 928
  • 7
  • 17
  • 2
    This might help: [How to get error message when ifstream open fails](http://stackoverflow.com/a/17338934/669576) – 001 Apr 08 '16 at 03:15
  • 2
    You might find it useful to have your `"Unable to open..."` print `filename` and the current working directory, as that's where it'll be looking for the file. If you're running your program from an IDE, it may not be where you expect. – Tony Delroy Apr 08 '16 at 03:16

1 Answers1

0

I ran the code myself and it is working fine. List your programming environment and what steps did you follow.Please make your question more elaborate and explain exactly what have you tried for making it work.

Please make sure the following:

  1. Try using the full path name; for example,

ifstream in("C:/someDirectory/andSomeOtherDirectory/one.txt");

  1. Try changing the spelling of the file.

For example:

"One.txt"

or

"ONE.txt"

  1. You need permission to read the file. Try changing the permission of file.

  2. Try different compilers

  3. Also if you use exception handling (try, throw, catch) instead of if, else that will help finding the error.

scai
  • 20,297
  • 4
  • 56
  • 72