Read Only File System with OfStream - c++11

I am trying to write to a file with ofstream in c++. It tells me that it is a "Read Only File System". I am able to make files outside of C++ -- i.e. other languages and with touch. Where path is "/home/<username/file.textpb" in my case it is "/home/andrew/file.textpb".
#include <fstream>
#include <iostream>
#include <string>
int main(int argc, char **argv) {
std::ofstream file("/home/andrew/file.textpb", std::ofstream::out);
if (file.fail()) {
std::cerr << "Write Error: " << strerror(errno) << std::endl;
} else {
file << "Some Text";
file.close();
}
return 0;
}

Related

How to convert boost::posix_time::ptime to YYMMDDHHMM?

I am trying to convert boost::posix_time::ptime to YYMMDDHHMM format string. How to accomplish this?
Related: How to convert a boost::ptime to string
#include <iostream>
#include <cstdlib>
#include <string>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/format.hpp>
int main()
{
std::string submitDateString = "20190911T235959";
boost::posix_time::ptime submitPtime = boost::posix_time::from_iso_string( submitDateString );
// Use a facet to display time in a custom format (only hour and minutes).
std::stringstream sstream;
boost::posix_time::time_facet* facet = new boost::posix_time::time_facet();
facet->format("%y%m%d%H%M");
sstream.imbue(std::locale(std::locale::classic(), facet));
sstream << submitPtime;
std::cout << "submit date:" << sstream.str( ) << std::endl;
}

serialize temporary into boost archive

The following is not possible for any boost output archive:
int foo(){
return 4;
}
ar << static_cast<unsigned int>(foo());
Is there an alternative without out creating a local temporary x=foo().
and why is the underlying archive operator <<(T & t) not const reference , for an output archive such that the above would work?
This seems to work, and I think this is why:
... To help detect such cases, output archive operators expect to be
passed const reference arguments.
It seems worth noting that in your example ar << foo(); does not work either (i.e. it doesn't have to do with your cast).
#include <fstream>
#include <iostream>
#include <boost/serialization/serialization.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
unsigned int foo(){
return 4;
}
int main()
{
{
std::ofstream outputStream("someFile.txt");
boost::archive::text_oarchive outputArchive(outputStream);
outputArchive << static_cast<const int&>(foo());
}
std::ifstream inputStream("someFile.txt");
boost::archive::text_iarchive inputArchive(inputStream);
int readBack;
inputArchive >> readBack;
std::cout << "Read back: " << readBack << std::endl;
return 0;
}

Retrieving VolumeDetails of WINDOWS Drives - stuck with 'char []' to 'LPCWSTR' conversion

I am trying to get the VolumeDetails of my WINDOWS system- Drive label plus its respective Volume Serial number. I've tried since an hour and built a code which gone wrong in syntax. At present I am getting the following error with it-
error C2664: 'GetVolumeInformationW' : cannot convert parameter 1 from 'char []' to 'LPCWSTR'
Here is my code:
// getVolDrive.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <direct.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <sstream>
#include <string>
#include <ctype.h>
#include <algorithm>
using namespace std;
//wchar_t mydrives[5];// = " A: ";
char mydrives[] = " A: ";
string retVolSno(char drives[]) //wchar_t drives[]
{
DWORD dwSerial;
stringstream ss;
cout<<drives<<endl;
if(!GetVolumeInformation(drives, NULL, 0, &dwSerial, NULL, NULL, NULL, 0))
{
ss<<"Error: "<<GetLastError();
}
else
{
ss<<hex<<dwSerial;
}
return ss.str();
}
int _tmain(int argc, _TCHAR* argv[])
{
string cVolSno;
ULONG DriveMask = _getdrives();
if(DriveMask == 0)
printf("_getdrives() failed with failure code: %d\n", GetLastError());
else
{
printf("This machine has the following logical drives:\n");
while (DriveMask)
{
cout << "In While" << endl;
if(DriveMask & 1)
printf("%s", mydrives);
wcout << mydrives << endl;
cVolSno = retVolSno(mydrives);
cout<<cVolSno<<endl;
++mydrives[1];
DriveMask >>= 1;
}
}
//std::transform(cVolSno.begin(), cVolSno.end(),cVolSno.begin(), ::toupper);
//cout<<cVolSno<<endl;
_getch();
return 0;
}
I've also tried replacing char with wchar_t, I didn't got any build errors, but while executing the application, got Error Code 3- Path not found!.
CODE MODIFIED:
// getVolDrive.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <direct.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <sstream>
#include <string>
#include <ctype.h>
#include <algorithm>
using namespace std;
//wchar_t mydrives[5];// = " A: ";
char mydrives[] = " A:\\\\ ";
string retVolSno(char drives[]) //wchar_t drives[]
{
DWORD dwSerial;
stringstream ss;
wchar_t text[10];
mbstowcs(text,drives,100); //strlen(drives)+1
LPWSTR ptr = text;
if(!GetVolumeInformation(ptr, NULL, 0, &dwSerial, NULL, NULL, NULL, 0))
{
ss<<"Error: "<<GetLastError();
}
else
{
ss<<hex<<dwSerial;
}
return ss.str();
}
int _tmain(int argc, _TCHAR* argv[])
{
string cVolSno;
ULONG DriveMask = _getdrives();
if(DriveMask == 0)
printf("_getdrives() failed with failure code: %d\n", GetLastError());
else
{
printf("This machine has the following logical drives:\n");
while (DriveMask)
{
if(DriveMask & 1)
printf("%s \n", mydrives);
cVolSno = retVolSno(mydrives);
std::transform(cVolSno.begin(), cVolSno.end(),cVolSno.begin(), ::toupper);
cout<<cVolSno<<endl;
++mydrives[1];
DriveMask >>= 1;
}
}
//std::transform(cVolSno.begin(), cVolSno.end(),cVolSno.begin(), ::toupper);
//cout<<cVolSno<<endl;
_getch();
return 0;
}
OUTPUT:
This machine has the following logical drives:
ERROR: 123
ERROR: 123
C:\\
ERROR: 123
D:\\
ERROR: 123
E:\\
ERROR: 123
I see at least these main issues:
1) wchar_t is the right type because you're compiling for UNICODE, you can write generic code using TCHAR macro or explicitly declare your buffer as wchar_t but that's what to do.
2) You have that error because you're passing wrong path to GetVolumeInformation() (trailing backslash is required so A: must become A:\).
Moreover please note that you have a little bit more easy way to achieve same result, you can use GetLogicalDriveStrings() to directly get a NULL delimited string list. Split it using, for example, this (don't forget UNICODE) and use c_str() with each entry.
EDIT about your modified code:
Why you drive path is A:\\ (escaped to A:\\\\)? Just one trailing backslash is needed so mydrives has to be declared as:
wchar_t mydrives[] = L"A:\\";
EDIT 2: there are more errors in your code so I'll post a reviewed version. There are more things I'd change but I'll point out just what doesn't actually work.
Function retVolSno to read volume serial number. Original version were almost right, in your modified version you perform useless character conversion. What you had to do was just to accept a wchar_t drive path.
Global variable mydrives. You actually don't need any global variable for that. It must be wchar_t and space before/after path are useless. One trailing backslash is needed. Line where you increment character value (++mydrives[0];) must be changed accordingly (index 0 instead of 1).
Check for drive availability. After if(DriveMask & 1) you did forget { then you won't print drive name but you'll perform GetVolumeInformation() even on unavailable drives (error 123). That's why indentation is important...
You're mixing UNICODE/NOT UNICODE and C/C++ stuff. I strongly suggest you pick one of them and you keep it (C or C++? UNICODE or NOT UNICODE?). For example you used C function printf() to print stuff and you have both std::string and wchar_t things.
Let's put everything together to have a working version. First the function to read serial number given drive path:
wstring getVolumeSerialNumber(const wchar_t* drivePath)
{
DWORD dwSerial;
wstringstream ss;
if (!GetVolumeInformation(drivePath, NULL, 0, &dwSerial, NULL, NULL, NULL, 0))
ss << L"Error: " << GetLastError();
else
ss << hex << dwSerial;
return ss.str();
}
It's almost the same as your original version, just changed to work with UNICODE characters. Then main function that cycles through available drives and print out their serial number:
int _tmain(int argc, _TCHAR* argv[])
{
wchar_t drive[] = L"A:\\";
ULONG driveMask = _getdrives();
if (driveMask == 0)
wcout << L"_getdrives() failed with failure code: " << GetLastError() << endl;
else
{
wcout << L"This machine has the following logical drives:" << endl;
while (driveMask)
{
if (driveMask & 1)
{
wcout << drive << endl;
wcout << getVolumeSerialNumber(drive) << endl;
}
++drive[0];
driveMask >>= 1;
}
}
wcin.ignore();
return 0;
}
From the documentation , the first parameters should be with trailing slash if drive letter is passed.
lpRootPathName [in, optional]
A pointer to a string that contains the root directory of the volume to be described.
If this parameter is NULL, the root of the current directory is used.
A trailing backslash is required.
For example, you specify \\MyServer\MyShare as \\MyServer\MyShare\, or the C drive as C:\

How do I create a file if the file does not exist?

I am currently trying to create a file after trying to open it, if it does not exist.
I would like to do this without the use of ios::app because with this, I would not be able to use the seek function in the future.
My includes:
#include <string>
#include <errno.h>
#include <fstream>
#inlcude <iostream>
using namespace std;
My main:
string str;
cout << "Enter a string: " << endl;
cin >> str;
fstream fstr;
fstr.open("test.txt", ios::in | ios::out | ios::binary | ios::ate );
if (fstr.fail()) {
cerr << strerror(errno) << endl;
fstr.open("test.txt", ios::out);
fstr.close();
fstr.open("test.txt", ios::in | ios::out | ios::binary | ios::ate );
} // if file does not exist, create by using "ios::out",close it, then re-open for my purpose
if (fstr.is_open()) { // if the file opens/exists
fstr << str << endl; // str goes into fstr
fstr.close(); // close
}
The code above seems to be working fine, but I just wanted to be open for any other advice, other suggestions or alternate methods of achieving the same goal. Thanks!
As an alternative, you could use the stat() function, which is available on Unix based systems and also Windows. Then you could write a very simple function that test if a filename exists and names a file:
#include <sys/stat.h>
bool FileExistAndIsFile(const std::string & filePath)
{
int result;
struct stat statBuf;
result = stat(filePath.c_str(), &statBuf);
return ((result == 0) && S_ISREG(statBuf.st_mode)) ? true : false;
}

Set Container Not Outpuitting Names

I have to use a set container with 10 names. It outputs "Myset contains" but doesn't list the names and I'm not sure why.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <set>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
std::string names[] = {"Nathan", "Dereck", "Robert", "Michael", "Elliot"
"Oliva", "Sophia", "Jessica", "Alexis", "Erin"};
//std::set <std::string> set(std::begin(names), std::end(names));
std::set<string> mynames (names, names);
std::cout << "Myset contains: ";
for (std::set<string>::iterator it=mynames.begin(); it!=mynames.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
int foo;
cin >> foo;
return 0;
}
Change:
std::set<string> mynames (names, names);
into:
std::set<string> mynames (names, names+number_of_elements);

Resources