0

I have a problem with reading lines from a .txt file in C++. The code is compiled with gmake on a FreeBSD environment.

So here is my code

int main(int argc, char **argv)
{
    std::string temp_value_line;
    std::string filename = "values.txt";
    std::ifstream open_file(filename.c_str());
    if (!open_file.is_open()) {
        sys_err("Failed to load values from values.txt");
        return 0;
    }
    int counter = 0;
    while (!open_file.eof())
    {
        open_file >> temp_value_line;
        str_to_number(common_value[counter], temp_value_line.c_str());
        counter++;
    }
    sys_log(0, "values loaded succsefully");
    open_file.close();
}

After building and running the application, there is the specified error message in my error log, so the file is not opened.

I already checked if there is a permissions or naming problem like "values.txt.txt" but everything seems to be okay. I am able to read/modify the file via console editor.

Thanks in advance.

Razvan Alex
  • 1,706
  • 2
  • 18
  • 21
Klappstuhl
  • 51
  • 2
  • 14
  • How do you run the program ? From what directory do you run it and which directory is `values.txt` in ? – Paul R Feb 18 '17 at 23:24
  • 3
    You should read [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – Thomas Matthews Feb 18 '17 at 23:29
  • The `values.txt` file is in the same directory as the program. I run the program/service with a start/stop script. – Klappstuhl Feb 18 '17 at 23:30
  • 1
    Easiest way to get a meaningful error message on why the file didn't open is to call `perror` – user4581301 Feb 18 '17 at 23:30
  • 1
    @Klappstuhl instead of use ` – user4581301 Feb 18 '17 at 23:30
  • 1
    From what folder does the start/stop script run the program? The program doesn't necessarily know where the executable is, but it does know what folder the executable was run from and that is where it is going to look for your file. – user4581301 Feb 18 '17 at 23:34
  • I have the `usr/home/Klappstuhl` directory. Inside that directory there is the script for starting the service and another folder, `Bin` which contains the .txt file and the application. @user4581301 – Klappstuhl Feb 18 '17 at 23:38
  • It sounds like you have a problem with the working directory - your script needs to set it correctly before running the program, e.g. `pushd Bin ; ./a.out ; popd`. – Paul R Feb 18 '17 at 23:46
  • Thanks everybody, I have fixed the problem. I was missing an `#include` in my cpp file but the compiler did not warn me about that. Now I will try to figure out how to mark this topic as solved. Again, thank you! – Klappstuhl Feb 18 '17 at 23:50

0 Answers0