In C++, opening a csv file with ifstream - c++

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

Related

How to save each string in a text file C++

I have a txt file, named mytext.txt, from which I want to read and save every line in C++. When I run the binary, I do ./file <mytext.txt
I'd like to do something
std::string line;
while(std::getline(std::cin,line)){
//here I want to save each line I scan}
but I have no clue on how to do that.
You can use a std::vector<string> to save the lines as so:
///your includes here
#include <vector>
std::vector<std::string> lines;
std::string line;
while(std::getline(std::cin,line))
lines.push_back(line);
You can look at the following documentation and example:
http://www.cplusplus.com/doc/tutorial/files/
Edit upon recommendation:
In the provided link below they explain how to open and close a text file, read lines and write lines and several other functionalities. For completeness of this answer an example will be given below:
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
The above script will write the 2 lines into the text file named example.txt.
You can then read these lines with a somewhat similar script:
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Best regards
Ruud

How do I write a string to a .csv file?

I currently have this code, but I would like to be able to output to a .csv file, rather than just print to screen. Does anyone know how to do this?
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
string Weather_test;
int main()
{
ifstream Weather_test_input;
Weather_test_input.open("/Users/MyName/Desktop/Weather_test.csv");
getline(Weather_test_input, Weather_test, '?');
Weather_test.erase(remove_if(Weather_test.begin(), Weather_test.end(), ::isalpha), Weather_test.end());
cout << Weather_test;
return 0;
}
If the Weather_test string is formatted properly.
ofstream Weather_test_output("path_goes_here.csv", ios::app);
// this does the open for you, appending data to an existing file
Weather_test_output << Weather_test << std::endl;
Weather_test_output.close();
If it is not formatted properly then you need to separate it into "fields" and write them with commas between them. That's a separate question.
Writing a string to a CSV file is like writing a string to any file:
std::string text = "description"
output_file << description << ", " << 5 << "\n";
In your example, you can't write to an ifstream. You can write to ofstream and fstream but not ifstream.
So either open the file for reading and writing or close after reading and open as writing.
To write to csv is to create an ostream and open file named "*.csv". You can use operator<< on this object in the same way as you have used it previously to write to the standard output, std::cout:
std::ofstream f;
f.open( "file.csv", std::ios::out);
if ( !f) return -1;
f << Weather_test;
f.close();
Thanks people you here are all truly amazing!
I managed to get my final piece of code which (removes all letters of the alphabet from my .csv file). Here it is for posterity
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
string Weather_test;
int main()
{
ifstream Weather_test_input;
Weather_test_input.open("/Users/MyName/Desktop/Weather_test.csv");
getline(Weather_test_input, Weather_test, '?');
Weather_test.erase(remove_if(Weather_test.begin(), Weather_test.end(), ::isalpha), Weather_test.end());
ofstream Weather_test_output("/Users/MyName/Desktop/Weather_test_output.csv", ios::app);
Weather_test_output << Weather_test << std::endl;
Weather_test_output.close();
cout << Weather_test;
return 0;
}
Thanks again all!

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.

Reading a file to a string in C++

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

Creating files in C++

I want to create a file using C++, but I have no idea how to do it. For example I want to create a text file named Hello.txt.
Can anyone help me?
One way to do this is to create an instance of the ofstream class, and use it to write to your file. Here's a link to a website that has some example code, and some more information about the standard tools available with most implementations of C++:
ofstream reference
For completeness, here's some example code:
// using ofstream constructors.
#include <iostream>
#include <fstream>
std::ofstream outfile ("test.txt");
outfile << "my text here!" << std::endl;
outfile.close();
You want to use std::endl to end your lines. An alternative is using '\n' character. These two things are different, std::endl flushes the buffer and writes your output immediately while '\n' allows the outfile to put all of your output into a buffer and maybe write it later.
Do this with a file stream. When a std::ofstream is closed, the file is created. I prefer the following code, because the OP only asks to create a file, not to write in it:
#include <fstream>
int main()
{
std::ofstream { "Hello.txt" };
// Hello.txt has been created here
}
The stream is destroyed right after its creation, so the stream is closed inside the destructor and thus the file is created.
#include <iostream>
#include <fstream>
int main() {
std::ofstream o("Hello.txt");
o << "Hello, World\n" << std::endl;
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string filename = "/tmp/filename.txt";
int main() {
std::ofstream o(filename.c_str());
o << "Hello, World\n" << std::endl;
return 0;
}
This is what I had to do in order to use a variable for the filename instead of a regular string.
Here is my solution:
#include <fstream>
int main()
{
std::ofstream ("Hello.txt");
return 0;
}
File (Hello.txt) is created even without ofstream name, and this is the difference from Mr. Boiethios answer.
If you want to create a file with some content and don't need to deal with the ofstream after that you can simply write:
#include <fstream>
int main() {
std::ofstream("file.txt") << "file content";
}
no need to manually close the file, deal with variables, etc. The file is created, written, and closed in the same line.
/*I am working with turbo c++ compiler so namespace std is not used by me.Also i am familiar with turbo.*/
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
#include<fstream.h> //required while dealing with files
void main ()
{
clrscr();
ofstream fout; //object created **fout**
fout.open("your desired file name + extension");
fout<<"contents to be written inside the file"<<endl;
fout.close();
getch();
}
After running the program the file will be created inside the bin folder in your compiler folder itself.
use c methods FILE *fp =fopen("filename","mode");
fclose(fp);
mode means a for appending
r for reading ,w for writing
/ / using ofstream constructors.
#include <iostream>
#include <fstream>
std::string input="some text to write"
std::ofstream outfile ("test.txt");
outfile <<input << std::endl;
outfile.close();