简体   繁体   中英

C++, How to open a file without having to type the whole file path

I have a simple question!

I am opening a file that is located in a simple folder in my VS12 project.

In order to open the file, you have to type in the whole file path so for example you would have to type:

TXTFiles//txtfile.txt

and then it successfully opens the file!

Well, i don't feel like typing in the whole file path and I've seen it before where it has already been added to the char or something so all you have to type in is the file you want to open but I can't remember how!

Example code:

char filename[256];

cout << " Enter a file to open" << endl;

cin >> filename;

example typed in: TXTFiles//object.txt

file opens, with more code added of course.

I don't want to have to type in the entire file path due to the fact that the file path may be long and tedious to type in, and one small mistake wont let you open the file.

I want to just type in 'object.txt' and open that file.

It's a simple thing for convenience, but I want just wondering!

Thank you.

#include <iostream>
#include <string>
int main() {
        std::string basename, path;
        std::cout << " Enter a file to open" << std::endl;
        std::cin >> basename;
        path = "TXTFiles/" + basename;
        std::cout << path << std::endl; // or, open file by 'path'
        return 0;
}

Or if you really want to use a char array:

#include <iostream>
#include <string.h>
int main() {
        char filename[256] = "TXTFiles/";
        std::cout << " Enter a file to open" << std::endl;
        std::cin >> (filename + strlen(filename));
        std::cout << filename << std::endl;
        return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM