Faced such a problem, I can not find how to solve it. The program asks to enter the name of the file to search for it on the disk. But the fact is that you have to enter the full path to the file, for example "C: \ PRIMER.txt".

Question: how to add a program so that you do not need to enter the full path, but only "PRIMER".

#include <iostream> // std::cout, std::cin #include <fstream> // std::ifstream #include <clocale> // setlocale( LC_ALL, "Rus" ); #include <cstdlib> // system( "pause" ); int main(int argc, char * argv[]) { setlocale(LC_ALL, "Rus"); char file_name[24]; std::cout << "Введите имя файла: "; std::cin >> file_name; std::ifstream file; do { std::cout << "\nФайл не найден.\n" << "Введите имя файла: "; std::cin >> file_name; file.open(file_name); if (file.good()) break; } while (true); char strBuff[124][124]; int n_strok = 0; std::cout << "\n"; while (!file.eof()) { file.getline(strBuff[n_strok], sizeof(strBuff[n_strok])); std::cout << n_strok + 1 << " " << strBuff[n_strok] << "\n"; ++n_strok; } std::cout << "\n"; system("pause"); return 0; } 
  • And where should it look for it only by name, and even without an extension? - Vladimir Martyanov
  • And why is OpenDialog not suitable for you? There is nothing at all, just click with the mouse. - BuilderC

2 answers 2

You can do it yourself with input, whatever. I would do that. 1. If the file goes without a path - that is, roughly speaking, without : \ ( / ) - then look for it in some default location (or just in the current directory). 2. If the file has no extension, add some default extension.

For example, if the default directory is C:\ABC , and the default extension is .txt , then there should be something like

 readme -> .\readme.txt readme. -> .\readme. up\readme.c -> up\readme.c 

Something like this ...

And I’ve already added the checks, and I think you can add the second piece to the line as well ...?

  • I got the idea. But I didn’t quite understand where to insert it - ADDO BOSS
  • @ADDOBOSS After the user has entered the file name. Between std::cin >> file_name; and file.open(file_name); - Harry
  • Error 3 error C2017: invalid escape sequence Error 1 error C2227: the expression to the left of "-> C" should indicate the type of a class, structure or union, or the universal type - ADDO BOSS
  • std :: cin >> file_name; file_name -> file_name.txt; file.open (file_name); - ADDO BOSS
  • @ADDOBOSS Are you kidding me, huh? :) file_name -> file_name.txt; - like this: if (file_name.find(".") == string::npos) file_name += ".txt"; - i.e. if there is no dot in the name - add extension ... - Harry

You can suggest a choice of directories on output, or you can do concatenation for file_name , to the main path

 std::cin >> file_name; file.open("C:\" + file_name + ".txt"); 

True file_name need to do the type string .