C++ file won't open - c++

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);
}

Related

In C++, opening a csv file with ifstream

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

Getting files from sub-directory using a string variable as filepath - C++

I have a sub directory in my projects main directory called 'data'. In this directory, are some csv files as well as a text file, and the text file contains the names of some csv files that I want to read data from. Using a while loop, I want to get each file name from the text file 'infile', store it into a string 'files', and use this string variable to open each file in the sub directory. I just dont know how I can access the sub directory using this string variable. What I have done in the code below, is move the files that I want to use into my main directory and it works as intended, but I want to achieve the same thing by just accessing the sub directory. Any suggestions?
string files;
ifstream infile("data\\met_index.txt"); //Open the text file that shows the csv files needed
if(!infile) //Exits the program and outputs this message if the file is not found
{
cout << "File not found.";
return -1;
}
Vector<string> headers; //A vector of type String to hold the headers for each column
while(getline(infile, files))
{
ifstream datafile(files.c_str()); // How do I access sub directory here?
if(!datafile) //Exits the program and outputs this message if the file is not found
{
cout << "File not found.";
return -1;
}
cout << "File: " << files << endl;
}
If you can use C++17 and your compiler supports the filesystem library, you should use it for better portability.
#include <iostream>
#include <string>
#include <vector>
#include <filesystem>
#include <fstream>
namespace fs = std::filesystem;
int main() {
const fs::path directory_path = "data";
std::ifstream infile{directory_path / "met_index.txt"};
if (!infile){
std::cerr << "met_index.txt not found!\n";
return -1;
}
std::vector<fs::path> file_paths{};
std::string file_input;
while(std::getline(infile, file_input)) {
const fs::path file_path = directory_path / file_input;
if(fs::exists(file_path)) {
file_paths.push_back(file_path);
}
}
for(const fs::path& file_path : file_paths) {
std::cout << file_path << '\n';
}
}
Remember you need to give your compiler flags to compile with C++17, and if you're using g++ or clang++ you might need to link filesystem with -lstdc++fs.
Also, if you're using your met_index.txt file only to store and read the files you have in your data directory so you can easily access them, you should look at directory_iterator to get files inside a directory.
As I understand it, you just want to build the file path accordingly.
For example, this could look like this:
std::string line;
while(std::getline(infile, line))
{
std::string filepath("data/");
std::ifstream datafile(filepath.append(line).c_str());
As AskoldIlvento already suggested, you should (if possible) use std::filesystem etc. for better compatibility. Or using a library like boost (boost::fileystem).
The ifstream constructor accepts either a char * or a const std::string & argument, so you have no reason to use ._str(). You could simply change your line with:
ifstream datafile(std::string("data\\") + files);
if(!datafile) //Exits the program and outputs this message if the file is not found
{

Having trouble opening a text file using ifstream in C++

I am working on a text processor that takes in text from a file and inserts it into a Graph data structure. I made the Graph, but I am having trouble with the text processor. Whenever I execute the code, it says I am unable to open the file. I made sure that the text file was in the same directory when I executed the code. Here is the code for the GraphTextProcessor class:
#include <fstream>
#include <cstring>
#include <string>
#include "Graph.h"
class GraphTextProcessor {
private:
Graph* m_data;
public:
GraphTextProcessor();
Graph* process(std::string filename);
};
GraphTextProcessor::GraphTextProcessor() {
}
Graph* GraphTextProcessor::process(std::string filename) {
//process text file and insert into graph here
std::string word;
//opens file in read mode
std::ifstream readFile;
readFile.open(filename.c_str(), std::ios::in);
if (readFile.is_open()) { //Not opening
while (readFile >> word) {
std::cout << word << std::endl;
}
// Closes open text file
readFile.close();
}
else {
std::cout << "Unable to open text file." << std::endl;
}
return NULL;
}
I am just trying to read from a file first before I actually try writing to the Graph. Here is the code that I am running in Main:
#include <iostream>
#include <string>
#include "GraphTextProcessor.h"
int main() {
GraphTextProcessor *gp = new GraphTextProcessor();
gp->process("hello.txt");
}
It prints "Unable to open text file". Any suggestions?
I ran the code myself and it is working fine.
List your programming environment and what steps did you follow.Please make your question more elaborate and explain exactly what have you tried for making it work.
Please make sure the following:
Try using the full path name; for example,
ifstream in("C:/someDirectory/andSomeOtherDirectory/one.txt");
Try changing the spelling of the file.
For example:
"One.txt"
or
"ONE.txt"
You need permission to read the file. Try changing the permission of file.
Try different compilers
Also if you use exception handling (try, throw, catch) instead of if, else that will help finding the error.

Read string from a file not working C++

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
}
// ...
}

can't open file ,mystate for datafile2 =2

When I debug this I can see it opens datafile1 , it reads the firstline and
in the logfile I get roma-3-4.log
It change to c:/temp/roma-3-4.log but when I want to open it , it fails. I have check that the _Mystate = 2 .
What is the meaning of that
Thanks
in the transfersubs.cfg there is this
roma-3-4.log
** In the directory c:/temp/ I have the following file
roma-3-4.log
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string input;
string logfile;
string errorfile;
short logfilesize1;
fstream dataFile1("c:/temp/transfersubs.cfg", ios::in);
if (dataFile1)
{
getline(dataFile1, input, '$');
logfile=input;
logfilesize1=input.size();
errorfile=input;
errorfile[logfilesize1-4]='e';
errorfile[logfilesize1-3]='r';
errorfile[logfilesize1-2]='r';
logfile="C:/Temp/"+logfile;
fstream dataFile2( logfile, ios::in);
if (dataFile2)
{
dataFile2.close();
}
else
{
cout << "ERROR: Cannot open logfile.\n";
}
dataFile1.close();
}
else
{
cout << "ERROR: Cannot open file.\n";
}
system("Pause");
return 0;
}
I believe your getline doesn't bother looking the newline but only for a $. You didn't post the file you are reading from, but check to ensure it has a $ at the end of the file name otherwise it will fetch the entire file.
It appears that unless you put a \n or endl after writing to the file using ofstream, ifstream won't be able to read anything from the file. In fact, adding a space after whatever you've written into file won't help either.
So always add a newline right after whatever it is that you've written to file using ofstream.