简体   繁体   English

C ++,如何在无需键入整个文件路径的情况下打开文件

[英]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. 我正在打开VS12项目中一个简单文件夹中的文件。

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 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! 好吧,我不想输入整个文件路径,并且在将其添加到char或其他内容之前,我已经看过它了,因此您只需输入要打开的文件即可,但是我可以记得如何!

Example code: 示例代码:

char filename[256]; 字符文件名[256];

cout << " Enter a file to open" << endl; cout <<“输入要打开的文件” << endl;

cin >> filename; cin >>文件名;

example typed in: TXTFiles//object.txt 输入的示例: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. 我只想输入“ object.txt”并打开该文件。

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: 或者,如果您真的想使用char数组:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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