C++ 从文本文件读取不起作用C++;

C++ 从文本文件读取不起作用C++;,c++,ifstream,C++,Ifstream,我只是想从文件中读取文本,不知道为什么代码不起作用。我已经将正确的文本文件名放在程序运行的文件夹中。我一定在做些小事。请在下面的代码中突出显示问题: // ConsoleApplication1.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <fstream> #include <string

我只是想从文件中读取文本,不知道为什么代码不起作用。我已经将正确的文本文件名放在程序运行的文件夹中。我一定在做些小事。请在下面的代码中突出显示问题:

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

#include<cstdio>

using namespace std;

#ifdef WIN32
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif

std::string get_working_path() {
    char cwd[1024];
    if (GetCurrentDir(cwd, sizeof(cwd)) != NULL)
        return std::string(cwd);
    else
        return std::string("");
}

int main() {

    string line;
    //ofstream myfile;
    //myfile.open("cmesymbols.txt", ios::out | ios::app | ios::binary);
    ifstream myfile("cmd.txt");

    if (myfile.is_open()) {
        while (getline(myfile, line))
        {
            cout << line << '\n';
        }
        myfile.close();
    }
    else
        std::cout << "File not found in cwd: " << get_working_path();

    myfile.close();

    return 0;



}
//ConsoleApplication1.cpp:定义控制台应用程序的入口点。
//
#包括“stdafx.h”
#包括
#包括
#包括
#包括
使用名称空间std;
#ifdef WIN32
#包括
#定义GetCurrentDir\u getcwd
#否则
#包括
#定义GetCurrentDir getcwd
#恩迪夫
std::string get_working_path(){
char-cwd[1024];
if(GetCurrentDir(cwd,sizeof(cwd))!=NULL)
返回标准::字符串(cwd);
其他的
返回std::字符串(“”);
}
int main(){
弦线;
//流文件;
//打开(“cmesymbols.txt”,ios::out | ios::app | ios::binary);
ifstream myfile(“cmd.txt”);
如果(myfile.is_open()){
while(getline(myfile,line))
{
cout
ifstream myfile(“cmd.txt”);
不会为您创建文件。

因此,请确保文件“cmd.txt”与main.cpp(或主源文件)一起存在于项目目录中。

此代码工作正常。我发现计算机中的文件夹设置是为了隐藏已知的文件扩展名。我故意将名称设置为“cmd.txt”,但实际名称显示为“cmd.txt.txt”因为这个代码找不到这个文件


我将文件名更正为“cmd.txt”代码正在运行。

您是如何编译的?如果您使用的是MSV,则通常需要将文件放在源文件所在的同一目录中。我使用MSV编译,当我从命令提示符运行console exe时,文件夹将从exe文件夹中出来。当前的工作目录字符串为空,因为它在您的文件夹中r local project folder,因此它是默认的(并且不需要指定任何特殊的内容)。重点是,文件不在项目文件夹中(注意,例如,当使用VS时,您应该将使用的文件放在代码所在的位置,而不是可执行文件所在的位置)。只需写一个文件的完整路径。顺便说一句,您在输出中没有看到:函数
get\u working\u path()
没有返回路径。我尝试了完整路径,如“C:\\cmd.txt”、“C:\cmd.txt”并复制到.cpp文件旁边的项目文件夹中。真奇怪,为什么不工作.file已经在项目文件夹中,但仍然无法读取。@NeerajKaushik它对我有效。您确定.txt文件与main.cpp(或您的主源文件)在同一文件夹中吗?@NeerajKaushik它对我也有效。您没有将cmd.txt文件保存在prog.exe文件夹中。请重新检查。我尝试了这两个选项。这可能是与project相关的任何设置吗?或者是否有可能在此处附加project?您在哪个IDE上编程?例如Code::Blocks使用与.exe文件目录不同的文件夹作为执行目录.