简体   繁体   中英

Reading from text file is not working C++

I am simply want to read text from a file and don't know why code is not working. I have already put correct text file name on folder from where program is running. I must be doing something small. Please highlight issue in code below:

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



}

Output: File not found in cwd:

ifstream myfile("cmd.txt"); doesn't create the file for you.
So make sure the file "cmd.txt" exists in your project directory together with your main.cpp
(or main source file).

This code is working fine. I found that folder settings in machine is to hide known extensions of files. I deliberately put name as "cmd.txt" however actual name came up as "cmd.txt.txt" and because of this code is not finding this file..

I corrected file name as "cmd.txt" and the code is working now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM