I have a for loop (below) that should output several strings to several files using wofstream. Unfortunately, it creates the file but does not output the string to the file. The files are always empty. I've looked through a lot of similar questions with no luck. Any help would be greatly appreciated. I'm on a Windows 10 machine using Visual Studio 2015 to write a UWP app.
for (size_t k=0;k < vctSchedulesToReturn.size();k++)
{
auto platformPath = Windows::Storage::ApplicationData::Current->RoamingFolder->Path;
std::wstring wstrplatformPath = platformPath->Data();
std::wstring wstrPlatformPathAndFilename = wstrplatformPath + L"\\" + availabilityData.month + L"_" + std::to_wstring(availabilityData.year) + L"_" + std::to_wstring(k) + L"_" + L"AlertScheduleOut.csv";
std::string convertedPlatformPathandFilename(wstrPlatformPathAndFilename.begin(), wstrPlatformPathAndFilename.end());
std::wofstream outFile(convertedPlatformPathandFilename);
outFile.open(convertedPlatformPathandFilename);
std::vector<std::pair<wstring, wstring>>::iterator pairItr;
std::wstring strScheduleOutputString = L"";
for (pairItr = vctSchedulesToReturn[k].second.begin(); pairItr!=vctSchedulesToReturn[k].second.end(); pairItr++)
{
strScheduleOutputString += pairItr->first + L",";
}
strScheduleOutputString += L"\r\n";
for (pairItr = vctSchedulesToReturn[k].second.begin(); pairItr != vctSchedulesToReturn[k].second.end(); pairItr++)
{
strScheduleOutputString += pairItr->second + L",";
}
outFile << strScheduleOutputString;
outFile.flush();
outFile.close();
}
std::wofstream outFile(convertedPlatformPathandFilename);
This creates a new file, and opens it for writing.
outFile.open(convertedPlatformPathandFilename);
This attempts to open the same file stream for writing a second time. Because the file stream is already open, this is an error. The error sets the stream into a failed state, and all attempts to write to the stream will now fail.
This is how you end up with an empty output file. It gets created, and a duplicate, second attempt to open the same file stream object puts it into error state.
Related
I'm developing a little updater for my framework. In particular the file is written in C++ and when i try to download a file using the following code the fopen function returns NULL. But the thing is that i tested this software on different machines with the same OS (Windows 10) and on few of them they returns NULL, the others just download and write the file correctly. Do you have any ideas? I've also tried to TRIM the filename to avoid invisible characters. Here's the code to download the file i used:
std::vector<unsigned char> resp = http_request(url, "GET", NULL, NULL, "", user_agent);
if (resp.empty()) {
send_output("ERROR: No response while downloading: " + url);
return;
}
string filename = url.substr(url.rfind("/") + 1);
filename = trim(filename);
if (filename.empty()) {
filename = "downloaded";
}
FILE* f = fopen(filename.c_str(), "wb");
if (f == NULL) {
log("ERROR: Could not open file for writing: " + filename);
return;
}
fwrite(&resp[0], 1, resp.size(), f);
fclose(f);
Thanks guys for the help!
To dynamically open a FILE I am passing a QString full path.
If passed as a variable, the code fails.
If entered directy (not via a variable) everything works just fine. What is going on here?
QString outputfile_qstring("C:/temp/out.mp3");
qDebug()<<"Original output file " << outputfile_qstring;
const char* outputfile = outputfile_qstring.toLatin1().constData();
qDebug()<<"Trying to open output file " << outputfile;
fout = fopen(outputfile, "wb+");
bool fileIsOpen = (fout != 0);
if ( !fileIsOpen ){
errStr_ = "Error opening the output file " + outputfile_qstring;
Q_ASSERT(false && "Could not open output file");
return false;
}
The QString to const char * conversion always fails.
Original output file "C:/temp/out.mp3"
Trying to open output file ????????????????????????aSC,_??r
The problem is here:
const char* outputfile = outputfile_qstring.toLatin1().constData();
The toLAtin1 function returns a QByteArray by value. And since you don't save that object, it will be destructed once the expression is finished, leaving you with outputfile being an invalid pointer to non-existing data.
The simple solution is to use the expression outputfile_qstring.toLatin1().constData() directly in the call to fopen. Or not use fopen and the C file functions at all and only use Qt files.
My executable built in C++/WinAPI will check for a file placed in the same folder and I use PathFileExists for that. When I run it on a normal computer it finds the file but when I publish the executable on RemoteApp and I run it from Web Access the file is not found. What would I be missing?
// This is the file I want to find (located in the same directory as the EXE)
wstring myfile = L"myfile.conf";
BOOL abspath = FALSE;
// Trying to get the absolute path first
DWORD nBufferLength = MAX_PATH;
wchar_t szCurrentDirectory[MAX_PATH + 1];
if (GetCurrentDirectory(nBufferLength, szCurrentDirectory) == 0) {
szCurrentDirectory[MAX_PATH + 1] = '\0';
} else {
abspath = true;
}
if (abspath) {
// Create the absolute path to the file
myfile = L'\\' + myfile;
myfile = szCurrentDirectory + myfile ;
MessageBox(hWnd, ConvertToUNC(myfile).c_str(), L"Absolute Path", MB_ICONINFORMATION);
} else {
// Get the UNC path
myfile = ConvertToUNC(myfile);
MessageBox(hWnd, myfile.c_str(), L"UNC Path", MB_ICONINFORMATION);
}
// Try to find file
int retval = PathFileExists(myfile.c_str());
if (retval == 1) {
// Do something
} else {
// File not found
}
The ConvertToUNC function is copied from here.
What I see is that, although the executable lies somewhere else, the absolute path is considered to be C:\Windows. I really don't know what is causing this. The server is Windows 2012 R2 and, like I said, applications are run through RemoteApp Web Access. The returned UNC path is just the name of the file (no volume or folder)
is there any way to enable user to select file manually using GUI in my cpp console application with OpenCV? I've made some research but found no solution for such trivial task so far...
Thanks in advance,
JP
For this, you have to add any available gui library and handle the gui part with that keeping the image processing part to opnecv. ( For example, you can try Qt )
If you want to a simple file open dialog in Ubuntu, you can do this:
FILE *in;
if (!(in = popen(
"zenity --title=\"Select an image\" --file-selection",
"r"))) {
return 1;
}
char buff[512];
string selectFile = "";
while (fgets(buff, sizeof(buff), in) != NULL) {
selectFile += buff;
}
pclose(in);
//remove the "\n"
selectFile.erase(std::remove(selectFile.begin(), selectFile.end(), '\n'),
selectFile.end());
// path + filename + format
Mat image = imread(selectFile);
I'd like to log my data on my Arduino one file at a time. I'd like the filename to be a combination of the number of milliseconds that have passed + some ID. For example, GPS data would be millis()+"GPS".
I tried the following code, but it doesn't like the fact that I am using a String. I could use a char array, but the length would always be dynamic. Is there a way to do this with at string somehow?
static void writeToSD()
{
String logEntry = " GPS: ";
logEntry += GPSString;
String filename = String(millis());
filename += "GPS";
Serial.println(logEntry);
Serial.println(filename);
File dataFile = SD.open(filename, FILE_WRITE);
// If the file is available, write to it:
if (dataFile) {
dataFile.println(logEntry);
dataFile.close();
Serial.println("Closed");
}
// If the file isn't open, pop up an error:
else {
Serial.println("error opening file");
}
}
You could try the following
char fileNameCharArray[filename.length()];
filename.toCharArray(fileNameCharArray, filename.length())
File dataFile = SD.open(fileNameCharArray, FILE_WRITE);
sprintf (filename, "%ld-GPS", millis());
Note that the use of String on Arduino is discouraged because of the well documented memory leak/fragmentation problems.