0

I'm trying to create a simple terminal program that generates random Japanese Gojuōn. I have a source file, named "source", which looks something like this:

A I U E O 
Ka Ki Ku Ke Ko 
...
あ い う え お 
か き く け こ 
...

Now, I'm trying to read each line of content into a string variable, and print it out onto the screen, but I was not able to open the file. Here is my code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    ifstream source ("source");
    string line;
    if (source.is_open())
    {
        while (getline(source, line))
        {
            cout << line << "\n";
        }
        source.close();
    }
    else cout << "Unable to open file!\n";
}

When I ran the code on terminal, I got "Unable to open file!". The code was in the same directory as the source file.

user438383
  • 5,716
  • 8
  • 28
  • 43
Kocobo
  • 1
  • 1
    The file should be in the same folder as the exe, not the source unless they are the same. – 001 Jan 13 '22 at 19:28
  • @JohnnyMopp ...assuming that you `cd` into the directory that contains the exe before running it. – 0x5453 Jan 13 '22 at 19:30
  • @0x5453 Yes, whatever the current directory is for the exe. – 001 Jan 13 '22 at 19:31
  • It needs to be in the current directory, which could be unrelated to the source directory as well as the exe directory. Alternatively (and probably better) is to use a fully-qualified path to the file, so it works regardless of what the current directory is. – Raymond Chen Jan 13 '22 at 19:32
  • 1
    Does this answer your question? [How to get error message when ifstream open fails](https://stackoverflow.com/questions/17337602/how-to-get-error-message-when-ifstream-open-fails) – hyde Jan 13 '22 at 19:33
  • In Visual Studio Community / Pro / Enterprise the default working directory is set by an IDE variable $(ProjectDir) which is the same folder as the project and probably the same folder as the source code. In other IDEs the default location may be the folder containing the executable or possibly some other default. With this said if your code returns it can't open the file, that means it probably is not in the current working directory or is not named as you expect. It could also be a permissions problem or caused by your file manager trying to be helpful by hiding the extension of your files. – drescherjm Jan 13 '22 at 20:51

1 Answers1

0

Are you running from inside your IDE? This is a very common thing when using an IDE.

The current working directory when running from the IDE may not be what you think it is. Try changing the path to the file to be the absolute path so you KNOW it's finding it.

Joseph Larson
  • 8,530
  • 1
  • 19
  • 36