Im working on a system, where i want to incooporate a log in form of a .txt file.
This file should be created everytime the program is started, and will in the future be written to, when i've created all my errorcodes.
To keep these log files unique, i wanted to use timestamp. For getting these stamps i've used the following code:
string GetDateStamp() {
time_t now = time(0);
struct tm tstruct;
char stamp[80];
tstruct = *localtime(&now);
strftime(stamp, sizeof(stamp), "%Y-%m-%d-%X", &tstruct);
return stamp;
}
This function is then called in another function, where i check if the dir for the log is created, if it is not, then it creates it.
void OpenNewLogFile(string& filepath)
{
string datestamp;
string logpath = filepath + "Log\\";
if (_mkdir(logpath.c_str()) == 0)
{
cout << "dir created" << endl;
}
else if(_mkdir(logpath.c_str()) == EEXIST)
{
cout << "dir already exists" << endl;
}
else if (_mkdir(logpath.c_str()) == ENOENT)
{
cout << "path could not be found" << endl;
}
ofstream outfile;
datestamp = GetDateStamp();
string createFile="";
createFile = logpath + datestamp + ".txt";
cout << createFile << endl;
outfile.open(createFile);
}
The code is present in a header file, and called upon from my main cpp.
The output i get now, is the path as follows:
C:...\Log\2020-08-10-15:59:22.txt
but no .txt file appears in my log dir.
Maybe the solution is right in front of me, but sadly i cannot see it.
Hope some of you can help me out :-)
Related
Total newbie in c++
Here's my problem. I am trying to write a c++ prog that reads a path from a user and prints the contents of the direcory on the screen. I am able to read a directory and print it but I cannot make it read from the outside.
#include <iostream>
#include <dirent.h>
using namespace std;
int main()
{
struct dirent *entry;
int files = 0;
DIR *folder;
const char *path;
path = userdir();
folder = opendir(path);
if (folder == NULL)
{
cout << "Unable to open the directory \n\n";
return(1);
}
else
{
cout << "Directory opened\n\n";
}
while ((entry=readdir(folder)))
{
files++;
cout << "File " << files << " " << entry->d_name << endl;
}
closedir(folder);
return(0);
}
I just want to create a function that reads the path from the user and passes the value to the main function, but somehow the fact that "path" is a const char doesn't allow me to do it.
Apologies for my ignorance...my experience in c++ is just 2 days....
OK
I managed to get a bit further, and added the following funcion
char * userdir()
{
char * ppath;
cout << "\nInsert path\n";
getline(cin,ppath);
return ppath;
}
And now the error I get is :
In function 'char* userdir()':
[Error] no matching function for call to 'getline(std::istream&, char*&)'
NB: funcion placed before int main()
Since this is C++, you can do the following to read the path:
cin >> path;
I have a JSP to upload a file which works fine. After the file has been uploaded I am trying to open the file again using the file path saved from the form data.
However, the filepath variable shows fine but the ifstream fails. If the csvFileName variable is set manually to path + file name it works fine. Doing this on a MAC and trying to avoid using boost library.
form_iterator two = cgi.getElement("csvFileName");
csvFileName=two->getValue();
form_iterator three = cgi.getElement("csvFilePath");
filePath = three->getValue();
csvFileName.c_str();
ifstream thefile;
thefile.open(csvFileName);
cout << "Filename is: " << csvFileName << endl;
if (thefile.is_open())
{
cout << "<H1>It's working</H1>" << endl;
while ( getline (thefile,line) )
{
cout << line << '\n';
}
thefile.close();
}
else
{
cout << strerror(errno) << endl;
}
I want to store cookie for my commandline application, for now I am using a file base approach where in I am using a file to store the data returned by server for future use in my command line application and encrypt the file.
The code goes like this
if ((sHeader.find("Session_ID")) != std::string::npos)
{
int iFound1 = sHeader.find("{");
int iFound2 = sHeader.find("}", iFound1);
int iLen = iFound2 - iFound1 - 1;
std::string sessionID = sHeader.substr((iFound1 + 1), iLen);
if (!sessionIdSet)
{
std::ofstream outputFile;
outputFile.open("session.txt");
if (outputFile.is_open())
{
outputFile << "Session_ID = " << sessionID << "\n" ;
outputFile << "IP = " << cli.getIP() << "\n";
outputFile.close();
sessionIdSet = true;
}
}
}
What can be a better approach to do it,, one i found is using %appdata% but i need some mechanism that is independent of underlying platform.
IN IOS app, module written in C++ I am writing my data (map of basic strings and integers) to a text file. Using following method:
bool Recognizer::saveMap(const char * s)
{
if(trainingData.model && !trainingData.model.empty()) {
const string filename = string(s);
std::ofstream file(s, ios_base::trunc );
try{
if(! file.is_open())
{
file.open(s);
}
for (map<String,int>::iterator it=trainingData.idMap.begin(); it!=trainingData.idMap.end(); ++it)
{
cout << it->second << " " << it->first << endl;
file << it->first << endl << it->second << endl;
}
file.close();
}
catch(cv::Exception & e){
if(file.is_open())
file.close();
int code = e.code;
string message = e.err;
cerr << "cv::Exeption code: " << code << " " << message << endl;
return false;
}
std::streampos fileLength = iosFileSize(s);
cout << "Saved map to: " << filename << " length: " << fileLength << endl;
return true;
}
return false;
}
My contains one entry and console output indicates that two lines: string, string representing number have been written to my file.
Subsequent opening file for reading and reading using getline or using stream operator indicates that file is empty:
bool Recognizer::loadMap(const char * s)
{
std::streampos fileLenght = iosFileSize(s);
std::ifstream file(s, ios::in);
try{
if(file.is_open())
{
string name;
string lineName;
string lineTag;
int tag;
int count = 0;
while(getline(file,name))
{
if(getline(file,lineTag))
{
tag = stoi(lineTag,0,10);
count++;
cout << tag << " " << name << endl;
trainingData.idMap[name]=tag;
trainingData.namesMap[tag]=name;
}
}trainingData.personsCount=count;
file.close();
}
}
catch(cv::Exception & e){
if(file.is_open())
file.close();
int code = e.code;
string message = e.err;
cerr << "cv::Exeption code: " << code << " " << message << endl;
return false;
}
cout << "Loaded map from: " << s << " lenght: "<< fileLenght << endl;
return true;
}
I also copied from one of stackoverflow answers method returning file lenght and using it to verify lenghth of the file after write operation:
std::streampos iosFileSize( const char* filePath ){
std::streampos fsize = 0;
std::ifstream file( filePath, std::ios::binary );
fsize = file.tellg();
file.seekg( 0, std::ios::end );
fsize = file.tellg() - fsize;
file.close();
return fsize;
}
The file path passed to saveMap and loadMap seems to be legit. With path that the app could not write to, attempt to write caused exception.
There are no errors returned by write operation but both, attempts to read and iosFileSize() indicate that file is empty.
I am not sure if i need call file.open() and file.close() or file is open and closed automatically when output stream is created and later goes out of scope.
I experimented with those with the same result ( call to file.is_open returns true so the block calling file.open() is skipped.
What am I doing wrong?
I appreciate all responses.
It does not seem like you call file.flush(); anywhere in Recognizer::saveMap() after writing to the file stream. std::ofstream::flush() saves changes you've made to the file. Add file.flush(); between when you make changes to the code and when you close the file. See if that remedies your issue.
I also had the same issue. Using file.flush() everytime after you insert to a file can save your file.
However if you insert something like this, say,
file << "Insert This"; You will need to add file.flush().
But some people have issues, like if you just insert file << "Insert This" << endl; , this works fine. The key point here is that, std::endl calls flush() everytime it is used internally. you can say it is a shortend form of "\n" + flush().
I believe from looking at your code that you are overwriting your data when you open the file in the second program you should be using something like this.
std::fstream fs;
fs.open ("test.txt", ios::app)
instead of doing the ios::in
I am having some trouble with sprintf and fstream functions in order to create new text files for a POS program/check whether the file already exists. I don't know if i am doing something wrong because the same set of functions works fine in other places in my code...
This particular section of code is taking input from the user to create a details file, the name is made up of the first and last name details that were entered into the system. For some reason the new file is not being created. When I step through the program I can see that the custDetC variable is being filled with the correct data. I have also included the file existence check as it may or may not have something to do with the issue at hand...
Tony Mickel
sprintf(custDetC,"%s%s.txt", firstName.c_str(), lastName.c_str());
cout << custDetC << endl;
FileEX = FileExists(custDetC);
if (FileEX == true)
{
fopen_s(&custDetF,custDetC, "rt");
fprintf(custDetF, "%s %s\n", firstName, lastName);
fprintf(custDetF, "$d\n", phoneNo);
fprintf(custDetF, "%s $s\n", unitHouseNum, street);
fprintf(custDetF, "%s %s %d", suburb, state, postCode);
fclose(custDetF);
}
else
{
char *buf = new char[100];
GetCurrentPath(buf);
cout << "file " << custDetC << " does not exist in " << buf << endl;
}
}
bool FileExists(char* strFilename)
{
bool flag = false;
std::fstream fin;
// _MAX_PATH is the maximum length allowed for a path
char CurrentPath[_MAX_PATH];
// use the function to get the path
GetCurrentPath(CurrentPath);
fin.open(strFilename, ios::in);
if( fin.is_open() )
{
//cout << "file exists in " << CurrentPath << endl;
flag = true;
}
else
{
//cout << "file does not exist in " << CurrentPath << endl;
flag = false;
}
fin.close();
return flag;
}
You seem to be opening the file for reading, but you need to open it for writing.
Instead of "rt" use "wt" in fopen_s()