I have written this code to make a file with current date. It is working 100 percent fine but is this approach right? or is this solution optimum? Can anyone help me to come up with better solution if required?
What I have done here in this code.
Firstly I wrote date in a file named name.txt.
Then I read that file using getline function and stored in string variable s.(I used getline to make date in a single string)
Then I removed name.txt, because now it is useless.
Now I made a new file using c_style string s.c_str() and wrote something in file.( Note: s is a string variable containing date. )
Finally, I opened that file using s.c_str() to read the data in file.
#include <ctime>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//SHAKAS ULTIMATE CODE
int main()
{
string s;
time_t now = time(0);
tm *ltm = localtime(&now);
ofstream file;
file.open("name.txt");
if(file.is_open())
{
file<< ltm->tm_mday<<"-";
file<<1 + ltm->tm_mon<<"-";
file<<1900 + ltm->tm_year;
//file<<1 + ltm->tm_hour<<"_"; Uncomment it if you want hours/min/sec on the name of file
//file<<1 + ltm->tm_min<<"_";
//file<<1 + ltm->tm_sec;
}
else
cout<<"Unable to create file";
file.close();
ifstream i;
i.open("name.txt");
while(!i.eof())
{
getline(i, s);
}
i.close();
remove("name.txt");
ofstream fileC;
fileC.open(s.c_str()); //writing in file, just to check
fileC << "WHO IS THE BOSS...?";
fileC.close();
string a;
i.open(s.c_str());
while(!i.eof())
{
getline(i, a); //Opening that file again to check if its written
cout<<a;
}
i.close();
}
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'm having some problems reading a string into an array. my file contains the following strings running horizontally down the page.
File:
dog
cat
rabbit
mouse
Code:
#include <string>
int i = 0;
using namespace std;
int main()
{
FILE * input1;
fopen_s(&input1, "C:\\Desktop\\test.dat", "r");
string test_string;
while (!feof(input1)) {
fscanf_s(input1, "%s", test_string);
i++;
}
return 0;
}
Any advice would be appreciated, Thanks!
You should use ifstream and std::getline
Now, I'm going to walk you through reading lines from the file using ifstream
Include fstream to use ifstream.
#include <fstream>
Opening a file:
To open a file, create an object of ifstream, and call it's method open and pass the filename as parameter. ifstream opens a file to read from it. (To write in a file, you can use ofstream)
ifstream fin;
fin.open("C:\\Desktop\\test.dat");
Or you can simply pass the filename to the constructor to create an object of ifstream and open a file.
ifstream fin("C:\\Desktop\\test.dat");
Reading from the file:
You can use stream extraction operator (>>) to read from the file, just like you use cin
int a;
fin >> a;
To read a line from a file using the above created fin (using a char array)
char arr[100];
fin.getline(arr, 100);
Better yet, you should use std::string instead or char arrays, using std::string, you can read a line using std::getline
string testString;
getline(fin, testString);
Now, let's change your code to use ifstream and getline
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
int i = 0;
ifstream input1;
input1.open("C:\\Desktop\\test.dat");
string test_string;
while (getline(input1, test_string)) {
i++;
}
return 0;
}
My program will prompt user to input numbers and the program will calculate the multiplication of the numbers. I want to store my data into a csv file in this format
""00:01AM/02/05/14.csv""
This is to ensure that I can store my data into a new .csv file instead of the existing one each and every time I terminate my program.But my program is not outputting into a csv file due to some error that I could not fix.Im not sure what is causing this problem.
Here is my code :
#include <iostream>
#include <fstream>
#include <iomanip>
#include <locale>
#include <string>
#include <sstream>
#include <time.h>
using namespace std;
string get_time();
string get_date();
int main()
{ //I can compile the codes but it is not outputting into a csv file
string date,time,out;
float a,b,c;
ifstream indata;
ofstream outdata;
date=get_date();
time=get_time();
time=time+'/';
out=time+date;//combines data&time into 12:01AM/02/05/14.csv string form
cout<<out<<endl;
//outputs the data into a csv file--but it is not working
outdata.open(out.c_str());
outdata << "Num1,Num2,Answer" << endl;
while (!(a ==-100))
{
cout<<"Enter Num1:";
cin>>a;
if(a==-100)break;
cout<<"Enter Num2:";
cin>>b;
c=a*b;
outdata<<a<<","<<b<<","<<c<< endl;
}
system("pause");
return 0;
}
string get_date()//converts date to string
{
time_t now;
char the_date[15];
the_date[0] = '\0';
now = time(NULL);
if (now != -1)
{
strftime(the_date,15, "%d/%m/%y.csv", gmtime(&now));
}
return string(the_date);
}
string get_time()//converts time to stirng
{
time_t currtime;
struct tm * timeinfo;
char the_time [12];
time (&currtime);
timeinfo = localtime (&currtime);
strftime (the_time,12,"%I:%M%p",timeinfo);
return string(the_time);
}
Did you know that slash is a character that you cannot use in filenames? Slash aka '/' is the directory separator.
Even on Windows, because Windows tries to be at least a little bit compatible with Unix.
Also, this is a good lesson for you. Always check for error codes. You should have a check to see if your outdata.open succeeded.
I'm in a tutorial which introduces files (how to read from file and write to file)
First of all, this is not a homework, this is just general help I'm seeking.
I know how to read one word at a time, but I don't know how to read one line at a time, or how to read the whole text file.
What if my file contains 1000 words? It is not practical to read entire file word after word.
My text file named "Read" contains the following:
I love to play games
I love reading
I have 2 books
This is what I have accomplished so far:
#include <iostream>
#include <fstream>
using namespace std;
int main (){
ifstream inFile;
inFile.open("Read.txt");
inFile >>
Is there any possible way to read the whole file at once, instead of reading each line or each word separately?
You can use std::getline :
#include <fstream>
#include <string>
int main()
{
std::ifstream file("Read.txt");
std::string str;
while (std::getline(file, str))
{
// Process str
}
}
Also note that it's better you just construct the file stream with the file names in it's constructor rather than explicitly opening (same goes for closing, just let the destructor do the work).
Further documentation about std::string::getline() can be read at CPP Reference.
Probably the easiest way to read a whole text file is just to concatenate those retrieved lines.
std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
file_contents += str;
file_contents.push_back('\n');
}
I know this is a really really old thread but I'd like to also point out another way which is actually really simple... This is some sample code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("filename.txt");
string content;
while(file >> content) {
cout << content << ' ';
}
return 0;
}
I think you could use istream .read() function. You can just loop with reasonable chunk size and read directly to memory buffer, then append it to some sort of arbitrary memory container (such as std::vector). I could write an example, but I doubt you want a complete solution; please let me know if you shall need any additional information.
Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
freopen("path to file", "rb", stdin);
string line;
while(getline(cin, line))
cout << line << endl;
return 0;
}
The above solutions are great, but there is a better solution to "read a file at once":
fstream f(filename);
stringstream iss;
iss << f.rdbuf();
string entireFile = iss.str();
you can also use this to read all the lines in the file one by one then print i
#include <iostream>
#include <fstream>
using namespace std;
bool check_file_is_empty ( ifstream& file){
return file.peek() == EOF ;
}
int main (){
string text[256];
int lineno ;
ifstream file("text.txt");
int num = 0;
while (!check_file_is_empty(file))
{
getline(file , text[num]);
num++;
}
for (int i = 0; i < num ; i++)
{
cout << "\nthis is the text in " << "line " << i+1 << " :: " << text[i] << endl ;
}
system("pause");
return 0;
}
hope this could help you :)
hello bro this is a way to read the string in the exact line using this code
hope this could help you !
#include <iostream>
#include <fstream>
using namespace std;
int main (){
string text[1];
int lineno ;
ifstream file("text.txt");
cout << "tell me which line of the file you want : " ;
cin >> lineno ;
for (int i = 0; i < lineno ; i++)
{
getline(file , text[0]);
}
cout << "\nthis is the text in which line you want befor :: " << text[0] << endl ;
system("pause");
return 0;
}
Good luck !
Another method that has not been mentioned yet is std::vector.
std::vector<std::string> line;
while(file >> mystr)
{
line.push_back(mystr);
}
Then you can simply iterate over the vector and modify/extract what you need/
The below snippet will help you to read files which consists of unicode characters
CString plainText="";
errno_t errCode = _tfopen_s(&fStream, FileLoc, _T("r, ccs=UNICODE"));
if (0 == errCode)
{
CStdioFile File(fStream);
CString Line;
while (File.ReadString(Line))
{
plainText += Line;
}
}
fflush(fStream);
fclose(fStream);
you should always close the file pointer after you read, otherwise it will leads to error
I just want to read a txt file and receive a string file like that
Blob rgbBlob;
string strIccRGBFile = "./icc/RGB.icc";
string strIccRGBContent = LoadFile(strIccRGBFile);
rgbBlob.update(strIccRGBContent.c_str(), strIccRGBContent.length());
image.profile("ICM", rgbBlob);
How I implement LoadFile function
#include <fstream>
#include <string>
int main()
{
std::string buff;
std::fstream fs("filename",std::ios::in | std::ios::ate)
if(fs.is_open())
{
fstream::pos_type size = fs.tellg();
fs.seekg(0);
buff.resize(size);
fs.read(&buff[0],size);
}
std::cout << buff << endl;
}
this is an example of how to read a file in it's entirety to a string buffer. It should give you a good idea on how to proceed.