从文本文件中读取不适用于C ++

时间:2015-05-13 17:39:36

标签: c++ ifstream

我只想阅读文件中的文字,并且不知道为什么代码无效。我已经在正在运行程序的文件夹上放置了正确的文本文件名。我必须做一些小事。请在下面的代码中突出显示问题:

// 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中找不到文件:

2 个答案:

答案 0 :(得分:0)

ifstream myfile("cmd.txt");没有为您创建文件 因此,请确保文件&#34; cmd.txt&#34; 与main.cpp
(或主源文件)一起存在于项目目录中。

答案 1 :(得分:0)

此代码工作正常。我犯了非常愚蠢的错误:(。实际上我发现机器中的文件夹设置是隐藏文件的已知扩展名。我故意将名称设置为&#34; cmd.txt&#34;但实际名称出现为&#34; cmd .txt.txt&#34;由于此代码未找到此文件..

我将文件名更正为&#34; cmd.txt&#34;并且代码现在正在运行。

谢谢你们在这个问题上快速跳跃。