0

Hello stack overflow community. I came here as a last resort because i probably made a stupid mistake i cannot see myself.

The question im asking is for some reason when i try to read a file with an absolute path(or relative, you can see i tried that in my code) it cannot read the file for some unknown reason(atleast to me). This is a small thing for a big project im working on. Thank you guys!

main.cpp

#include <iostream>
#include <fstream>
#include <filesystem>
#include <unistd.h>
#include <string>
std::string openf() {
    FILE* pipe = popen("zenity --file-selection", "r"); // open a pipe with zenity
    if (!pipe) return "ERROR"; // if failed then return "ERROR"
    char buffer[912]; // buffer to hold data
    std::string result = ""; // result that you add too

    while(!feof(pipe)) { // while not EOF read
        if(fgets(buffer, 912, pipe) != NULL) // get path and store it into buffer
            result += buffer; // add buffer to result
    }

    //I thought i needed to convert the absolute path to relative but i did not after all
    // char cwd[10000];
    // getcwd(cwd, 10000); // get cwd(current working directory)
    // result = std::filesystem::relative(result, cwd); // convert the absolute path to relative with cwd
    pclose(pipe); // cleanup
    return result;
}

std::string readf(std::string filename){
    std::string res;
    std::ifstream file;
    file.open(filename.c_str());
    if(file.is_open()) {
        while(file){
            res += file.get();
        }
    }else {
        std::cout << "failed to open file " + filename;
    }
    return res;
}

int main( void ){
    std::string file = openf();
    std::cout << file << std::endl;
    std::string str = readf(file);
    std::cout << str << std::endl;
    return 0;
}

output

/home/meepmorp/Code/Odin/test/test.odin

failed to open file /home/meepmorp/Code/Odin/test/test.odin
xd-sudo
  • 13
  • 3
  • Side note for later: [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) You get around some of this problem with the following `if`, but you can avoid it completely rather than dodging it. – user4581301 Jul 27 '21 at 18:49
  • See if calling [`perror`](https://en.cppreference.com/w/cpp/io/c/perror) before printing out the "failed to open" message gives you more information on the failure. – user4581301 Jul 27 '21 at 18:53

1 Answers1

3

It seems zenity, which you use as file chooser, outputs an extra newline after the file name, which you include in the name. In Linux, files can actually contain embedded newline characters in their name, and you actually try to open "test.odin\n" instead of "test.odin".

Michael Karcher
  • 3,803
  • 1
  • 14
  • 25