难以通过ifstream在C 中找到文件

trouble finding file in c++ via ifstream

本文关键字:文件 ifstream      更新时间:2023-10-16

我已经尝试了5次此程序,但仍然无法找到我提供的路径的文件。我如何指定文件路径

#include<iostream>
#include<conio.h>
#include<fstream>
#include<stdio.h>
#include<string.h>
using namespace std;
int main()
{
    ifstream infile("C:\UsersDellDocumentsVisual Studio 2017TemplatesProjectTemplatesVisual C++ Projecty.txt");
    char a[20];
    if (!infile)
        cout<<"file doesnt exists";
    else
        while (infile.getline(a, 20, '/n'))
        {
            cout << a;
        }
    _getche();
}

基本上如何指定文件路径

您必须逃脱文件路径中出现的所有后斜线,不仅是第一个:

ifstream infile("C:\Users\Dell\Documents\Visual Studio 2017\Templates\ProjectTemplates\Visual C++ Project\y.txt");
                       // ^     ^          ^                   ^  ...      

另一种方法是使用原始字符串文字:

ifstream infile(R"(C:UsersDellDocumentsVisual Studio 2017TemplatesProjectTemplatesVisual C++ Projecty.txt)");