Search code examples
c++windowscmakeioclion

How to link input text file to C++ program


I'm trying to write a C++ program in CLion that opens, manipulates, and closes an input file and output file. The input file is a .txt file, but when I execute the program, it can't find the input file even though it's in the same directory as the .cpp program it's executing from. I was wondering if it was because I had to link the input file with CMake, but I'm unfortunately unfamiliar with configuring CMake. How can I link a .txt file to a C++ project?


Solution

  • You don't "link" a text file to an executable file. In CLion, the default behavior is to build the project binary into a folder called cmake-build-debug. The text file you want to use as your input has to be in the same directory as the .exe file, not the .cpp, so what you would have to do in this case is prepend a ../ to the name of the text file (i.e... if your file is called input.txt, the C code would say something like

    FILE* input_file = fopen("../input.txt", "r");
    

    Remember to check for return codes, errors, etc.


    The above solution is not good for a variety of reasons; first of all, you're hard coding a filename, which is at best a huge limitation and at worst pointless. A better solution would be to pass in the name of the file via the command line.

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[])
    {
        if (argc != 2) { return EXIT_FAILURE; }
    
        FILE* inputFile = fopen(argv[1], "r");
    
        ...
    
        return EXIT_SUCCESS;
    }
    

    This solution is still not great, however, primarily because you should always sanitize your inputs, never just accepting string input from the user and simply using it right away. This is a huge security liability. I also didn't check return codes or anything; I simply verified argc was two. (Remember that a program will always have argc at least equal to 1, since the first argument is the program's name.)


    To answer your actual question (the one you asked, though not necessarily the one you needed an answer to), you can use CMake's find_file function to "link" to a file. You're not actually linking anything, really, the find_file function simply returns the full path to a named file, but you can then pass this information as a parameter to your program as discussed previously.

    You can do more than might be immediately obvious with CMake, actually; here is the documentation for their file-related functions.

    You can also execute your newly-built program from CMake directly, using the execute_process function. The function actually takes an INPUT_FILE parameter directly, so you can set a variable for the path of your input file, set it using the result of find_file, then directly execute the program with your input file using execute_process.