-1

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.

4

1 回答 1

2
#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;
}
于 2013-03-31T01:18:59.970 回答