I have this code in C++:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
string str;
ifstream file("file.txt");
file >> str;
cout << str;
return 0;
}
I have file.txt in the same directory as main.cpp. I get no output from this, I've tried specifying full filepath to the file and still no result and tried it on few different machines too.
Does anybody know what I'm doing wrong?
What you're interested in is the current working directory for your program, i.e. where your text file is supposed to be if you don't qualify it with a full or relative path.
You can get it at runtime with getcwd (linux) or _getcwd (windows).
Edit: I agree with Andy, you should anyway check for errors when opening files. You could have caught this earlier (i.e. file not found), e.g.
(pseudocode ahead for illustrative purposes)
#include <unistd.h>
// Warning: linux-only, use #ifdefs and _getcwd for windows OS
std::string get_working_path() {
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL)
return std::string(cwd);
else
return std::string("");
}
int main() {
std::string str;
std::ifstream file("file.txt");
if (file >> str)
std::cout << str;
else {
std::cout << "File not found in cwd: " << get_working_path();
// abort
}
// ...
}
Related
I am trying to open a csv file in C++ using ifstream with a directory in the file path name. The file does reside in the specified directory location, but I observe an for the variable inFile when executing the code. My research up to this point says the code is correct, but something obviously is wrong. Any suggestions?
Thanks,
KG
#include <string>
#include <fstream>
#include <iostream>
virtual void run()
{
string file_dir = "/home/datafiles/";
string csvFile = file_dir + "/myFile.csv";
ifstream inFile;
inFile.open("csvFile", ios::in);
// file check to see if file is open
if(!inFile.is_open()) {
cout << "error while opening the file" << endl;
}
}
I found the answer to my csv file opening problem, a colleague assisted.
#David - You suggested removing the double quotes in the "inFile.open" line of code. In addition to removing the double quotes, I also needed to add c_str(), which "returns a pointer to a null-terminated character array with data equivalent to those stored in the string," .data() also performs the same function (cppreference.com).
#user4581301 - I am also aware that ios::in is implied with a ifstream, only included it here as a reference; thanks.
The modified code is listed below:
#include <string>
#include <fstream>
#include <iostream>
virtual void run()
{
string file_dir = "/home/datafiles/";
string csvFile = file_dir + "/myFile.csv";
ifstream inFile;
inFile.open(csvFile.c_str(), ios::in);
// file check to see if file is open
if(!inFile.is_open()) {
cout << "error while opening the file" << endl;
}
}
Really appreciate all the help.
Enjoy,
KG
Is this what you're trying to do?
#include <iostream> // std::{ cout, endl }
#include <string> // std::{ string, getline }
#include <fstream> // std::ifstream
auto main() -> int {
// Just to demonstrate.
// You want to use your real path instead of example.cpp
auto file = std::ifstream("example.cpp");
auto line = std::string();
while ( std::getline(file, line) )
std::cout << line << '\n';
std::endl(std::cout);
}
Live example
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:
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.
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).
I am trying to bind input stream with a file stream , I hope that input something from input stream and then automatic flush to the file stream
It does not work...I enter something from keyboard , outfile is still empty
#include <iostream>
#include <fstream>
#include <stdexcept>
using namespace std;
int main(int argc, char const *argv[])
{
ofstream outfile("outfile" , ofstream::app | ofstream::out);
if(!outfile)
throw runtime_error("Open the file error");
ostream * old_tie = cin.tie();//get old tie
cin.tie(0);//unbind from old tie
cin.tie(&outfile);//bind new ostream
string temp;
while(cin >> temp)
{
if(temp == ".")//stop input
break;
}
cin.tie(0);
cin.tie(old_tie);// recovery old tie
return 0;
}
Your program is too complicated and is misusing tie(). Try the following:
#include <iostream>
#include <fstream>
int main() {
using namespace std;
ofstream outfile("outfile" , ofstream::app | ofstream::out);
if(!outfile) {
cerr << "Open the file error";
return 1;
}
char data(0);
while(data != '.') {
cin.get(data);
cin.clear(); // Prevents EOF errors;
outfile << data;
}
return 0;
}
It reads char by char until it finds a .
Errors:
why make throw exception if you don't catch it...
close file please
do you put data from file to temp and go through it to find "." and
end program?
Why do you use pointer for old_tie use it for the first ofstream file
like this ofstream * file.
fix if statement and break
include string library -- //This might solve your problem
what is filename??
is tie(0) function to unbind?
//EDIT
Explanation:
once you find first period with find_first_of function you create a substr and copy it into outfile. The Solution is so efficent and works every time. The logic is as simple as it can get. Don't use unnecessary functions and initialize unnecessary variables because it is more complex and more prone to errors when you have too many variables.
Solution: - No need for cin.tie()
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
ofstream outfile("outfile" , ofstream::app | ofstream::out);
string s;
getline(cin, s);
int i = s.find_first_of(".");
if(i!=std::string::npos)
{
s = s.substr(0, i);
outfile << s;
}
else
{
cout << "No periods found" << endl;
}
}
Compiled code - http://ideone.com/ooj1ej
If this needs explanation please ask questions in comments below.
I'm new to C++ and am trying to open a file, but can't get it to work. The file is definitely there, in the same directory. I have tried unhiding extensions (it's definitely called test.txt and not test.txt.txt for example), and also tried using the full path. The file is not open anywhere. Any ideas (I'm sure it's something simple but I'm stuck)?
string mostCommon(string fileName)
{
string common = "default";
ifstream inFile;
//inFile.open(fileName.c_str());
inFile.open("test.txt");
if (!inFile.fail())
{
cout << "file opened ok" << endl;
}
inFile.close();
return common;
}
If you specify inFile.open("test.txt") it will try to open "test.txt" in the current working directory. Check to make certain that is actually where the file is. If you use absolute or relative pathing, make sure that you use '/' or '\\' as the path separator.
Here is an example that works when a file exists:
#include <fstream>
#include <string>
#include <cassert>
using namespace std;
bool process_file(string fileName)
{
ifstream inFile(fileName.c_str());
if (!inFile)
return false;
//! Do whatever...
return true;
}
int main()
{
//! be sure to use / or \\ for directory separators.
bool opened = process_file("g:/test.dat");
assert(opened);
}
As somebody who is new to C++ and coming from a python background, I am trying to translate the code below to C++
f = open('transit_test.py')
s = f.read()
What is the shortest C++ idiom to do something like this?
The C++ STL way to do this is this:
#include <string>
#include <iterator>
#include <fstream>
using namespace std;
wifstream f(L"transit_test.py");
wstring s(istreambuf_iterator<wchar_t>(f), (istreambuf_iterator<wchar_t>()) );
I'm pretty sure I've posted this before, but it's sufficiently short it's probably not worth finding the previous answer:
std::ifstream in("transit_test.py");
std::stringstream buffer;
buffer << in.rdbuf();
Now buffer.str() is an std::string holding the contents of transit_test.py.
You can do file read in C++ as like,
#include <iostream>
#include <fstream>
#include <string>
int main ()
{
string line;
ifstream in("transit_test.py"); //open file handler
if(in.is_open()) //check if file open
{
while (!in.eof() ) //until the end of file
{
getline(in,line); //read each line
// do something with the line
}
in.close(); //close file handler
}
else
{
cout << "Can not open file" << endl;
}
return 0;
}