从文本文件中读取不起作用C

Reading from text file is not working C++

本文关键字:不起作用 读取 文本 文件      更新时间:2023-10-16

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

// 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;

}

输出:CWD中找不到的文件:

此代码工作正常。我发现机器中的文件夹设置是隐藏已知的文件扩展名。我故意将名称为" cmd.txt"但是,实际名称出现为" cmd.txt.txt"。而且由于此代码没有找到此文件。

i更正文件名为" cmd.txt"代码现在正在工作。

ifstream myfile("cmd.txt");不为您创建文件。
因此,请确保您的项目目录中存在文件" cmd.txt" 与您的main.cpp
(或主源文件)。