Search code examples
c++cmakeifstream

ifstream not reading anything


I'm writing code in C++ and I need to read a file, problem is my file structure is a bit complex and I just cannot figure out how to use my ifstream to read it. I think I tried all possible combinations... but it just doesn't work, I guess I'm doing something wrong but I can't figure it out.

Here is a minimal reproduction of my problem.

structure :

.
├── build
├── CMakeLists.txt
└── src
    ├── file
    │   └── test.txt
    ├── load
    │   └── loadfile.hpp
    └── main.cpp

CMakeLists.txt :

cmake_minimum_required(VERSION 3.10)
project(BaseProject)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_FLAGS "-O3 -g -std=c++17 -Wall -Wextra -pedantic")

file(GLOB SRC
        "src/*.h"
        "src/*.hpp"
        "src/load/*.h"
        "src/load/*.hpp"
        "src/load/*.cpp"
        )

add_executable(exec ${SRC} src/main.cpp)

main.cpp

#include "load/loadfile.hpp"

int main(){
    load();
    return 0;
}

test.txt : (not very relevent but meh)

test

loadfile.hpp

#include <fstream>
#include <string>
#include <iostream>

void loadFile(const std::string& file){
    std::ifstream i(file, std::ifstream::in);
    std::string str;
    i >> str;
    std::cerr << str;
    i.close();
}

void load(){
    loadFile("../file/test.txt");
}

output is empty and program finishes normally.


Solution

  • Answer from Some programmer dude in the comments:

    Now might be a good time to learn about the concept of current working directory. When you run a program, its process will have a current working directory. If you run from a console or terminal then it's usually the terminals current directory. Relative paths (paths not beginning with a /) are always relative to the current working directory. You need to make sure that the relative path in the program is valid for the programs current working directory when running.