Reputation: 354
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:
Upvotes: 0
Views: 20799
Reputation: 354
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.
Upvotes: 2
Reputation: 10998
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).
Upvotes: 0