How to check filename and variable name are same - c++11

Actually, the problem is, When system getting upgrade it should write "DISABLE_BACKUP" file in root directory. When it comes up, i have to check whether the file has been in root or not.
if ((dir = opendir ("/"))!=NULL)
{
while ((ent = readdir(dir)) != NULL)
{
printf ("%s\n", ent->d_name);
//Here i have to compare the filename (DISABLE_BACKUP) with the string "DISABLE_BACKUP" and has to raise log entry.
}
closedir(dir);
}

The C function for comparing strings is strcmp():
if (strcmp(ent->d_name, "DISABLE_BACKUP")==0) {
// Found it!
Perhaps a better way to see if the file "DISABLE_BACKUP" exists is access():
#include <unistd.h>
...
if (access(fname, F_OK) != -1) {
// file exists
} else {
// file doesn't exist
}

Related

OSX: shm_open returns ENAMETOOLONG

I am trying atm to create a shared memory file for my process. The filename constists of several parts to identify the process the SHM belongs to and whats its content. An example would be:
shm_pl_dev_system_25077
I create all the files in a directory I created in /tmp where I have full write and read permissions.
So the complete Path would be:
/tmp/pl_dev/shm_pl_dev_system_25077
I create several files there, some fifo pipes and other stuff and also the shm. The only Problem I get is that shm_open will always return the errno 63 (ENAMETOOLONG).
Can you tell me what the issue here is?
Here is the code:
handle_ = ::shm_open(shm_name.get(), O_RDWR, 0755);
if (handle_ == -1 && errno == ENOENT)
{
// SHM does not yet exists, so create it!
handle_ = ::shm_open(shm_name.get(), O_CREAT | O_RDWR, 0755);
if (handle_ != -1) {
created_ = true;
}
else
{
if (!silent_)
{
log.error("Couldn't create the SHM (%d).", errno);
}
return false;
}
}
Okay. As it seems OSX is very limited in the filename of SHMs... The maximum length for a filename currently is 31 chars per section (see PSHMNAMELENGTH in /usr/include/sys/posix_shm.h)

Same .txt files, different sizes?

I have a program that reads from a .txt file
I use the cmd prompt to execute the program with the name of the text file to read from.
ex: program.exe myfile.txt
The problem is that sometimes it works, sometimes it doesn't.
The original file is 130KB and doesn't work.
If I copy/paste the contents, the file is 65KB and works.
If I copy/paste the file and rename it, it's 130KB and doesn't work.
Any ideas?
After more testing it shows that this is what makes it not work:
int main(int argc, char *argv[])
{
char *infile1
char tmp[1024] = { 0x0 };
FILE *in;
for (i = 1; i < argc; i++) /* Skip argv[0] (program name). */
{
if (strcmp(argv[i], "-sec") == 0) /* Process optional arguments. */
{
opt = 1; /* This is used as a boolean value. */
/*
* The last argument is argv[argc-1]. Make sure there are
* enough arguments.
*/
if (i + 1 <= argc - 1) /* There are enough arguments in argv. */
{
/*
* Increment 'i' twice so that you don't check these
* arguments the next time through the loop.
*/
i++;
optarg1 = atoi(argv[i]); /* Convert string to int. */
}
}
else /* not -sec */
{
if (infile1 == NULL) {
infile1 = argv[i];
}
else {
if (outfile == NULL) {
outfile = argv[i];
}
}
}
}
in = fopen(infile1, "r");
if (in == NULL)
{
fprintf(stderr, "Unable to open file %s: %s\n", infile1, strerror(errno));
exit(1);
}
while (fgets(tmp, sizeof(tmp), in) != 0)
{
fprintf(stderr, "string is %s.", tmp);
//Rest of code
}
}
Whether it works or not, the code inside the while loop gets executed.
When it works tmp actually has a value.
When it doesn't work tmp has no value.
EDIT:
Thanks to sneftel, we know what the problem is,
For me to use fgetws() instead of fgets(), I need tmp to be a wchar_t* instead of a char*.
Type casting seems to not work.
I tried changing the declaration of tmp to
wchar_t tmp[1024] = { 0x0 };
but I realized that tmp is a parameter in strtok() used elsewhere in my code.
I here is what I tried in that function:
//tmp is passed as the first parameter in parse()
void parse(wchar_t *record, char *delim, char arr[][MAXFLDSIZE], int *fldcnt)
{
if (*record != NULL)
{
char*p = strtok((char*)record, delim);
int fld = 0;
while (p) {
strcpy(arr[fld], p);
fld++;
p = strtok('\0', delim);
}
*fldcnt = fld;
}
else
{
fprintf(stderr, "string is null");
}
}
But typecasting to char* in strtok doesn't work either.
Now I'm looking for a way to just convert the file from UTF-16 to UTF-8 so tmp can be of type char*
I found this which looks like it can be useful but in the example it uses input from the user as UTF-16, how can that input be taken from the file instead?
http://www.cplusplus.com/reference/locale/codecvt/out/
It sounds an awful lot like the original file is UTF-16 encoded. When you copy/paste it in your text editor, you then save the result out as a new (default encoding) (ASCII or UTF-8) text file. Since a single character takes 2 bytes in a UTF-16-encode file but only 1 byte in a UTF-8-encoded file, that results in the file size being roughly halved when you save it out.
UTF-16 is fine, but you'll need to use Unicode-aware functions (that is, not fgets) to work with it. If you don't want to deal with all that Unicode jazz right now, and you don't actually have any non-ASCII characters to deal with in the file, just do the manual conversion (either with your copy/paste or with a command-line utility) before running your program.

Boost GraphML reader and yEd

I am trying to read a .graphml that yEd (yEd) generates. I am able to read simple and manually-generated .graphml files but the yEd files contains several properties to be defined. Does any one has a running example that show how to deal with such yEd files?
The yED file must be filtered to remove all the yEd stuff that boost::read_graphml does not recognize. If all you want is the vertices and edges, this is simple enough. However, if you do want some of the attributes, then it becomes more complex, and will depend on what you need.
Here is some code that filters out all the yED stuff, except the text of the node labels, which is converted to the simplest possible node label attribute that boost::read_graphml can parse and store in a bundled property.
/**
Check for a yEd file
#param[in] n the filename
#return true if the file weas written by yED
The input file is copied to a new file graphex_processed.graphml
If the intput file was NOT produced by yEd, then the copy is perfect
If input was produced by yEd then the copy is filtered so that it can be
read by boost::read_graphml
Most of the yEd stuff is discarded, except for the node labels
the text of which are copied to a simple node attribute "label"
*/
bool cGraph::IsGraphMLbyYED(const std::wstring& n)
{
bool yEd = false;
// open the input file
std::ifstream fin;
fin.open(n.c_str(), std::ifstream::in);
if( ! fin.is_open() ) {
return false;
}
// open the output file
std::ofstream fout;
fout.open("graphex_processed.graphml", std::ifstream::out );
if( ! fout.is_open() ) {
return false;
}
// loop over input file lines
fin.clear();
char buf[1000];
while( fin.good() ) {
fin.getline( buf,999 );
std::string l( buf );
// check for file produced by yEd
if( l.find("<!--Created by yFiles") != -1 ) {
yEd = true;
// convert NodeLabel text to simple label attribute
fout << "<key id=\"key0\" for=\"node\" attr.name=\"label\" attr.type=\"string\" />\n";
}
// check for file already identified as yEd
if( yEd ) {
// filter out yED attributes
if( l.find("<key") != -1 ) {
continue;
}
// convert NodeLabel text
if( l.find("<y:NodeLabel") != -1 ) {
int p = l.find(">")+1;
int q = l.find("<",p);
std::string label = l.substr(p,q-p);
fout << "<data key=\"key0\">" << label << "</data>\n";
continue;
}
// filter out outher yEd stuff
if( l.find("<y:") != -1 ) {
continue;
}
if( l.find("</y:") != -1 ) {
continue;
}
if( l.find("<data") != -1 ) {
continue;
}
if( l.find("</data") != -1 ) {
continue;
}
}
// copy input line to output
fout << buf << std::endl;
}
// close files
fin.close();
fout.close();
// return true if yED file
return yEd;
}
Here is some code to read the filtered file
void cGraph::ReadGraphML(const std::wstring& n)
{
// check if file was produced by yEd
IsGraphMLbyYED( n );
boost::dynamic_properties dp;
dp.property("label", boost::get(&cVertex::myName, myGraph));
myGraph.clear();
std::ifstream fin;
fin.open("graphex_processed.graphml", std::ifstream::in);
if( ! fin.is_open() ) {
return;
}
boost::read_graphml( fin, myGraph, dp );
}
If you want to see an example of this running in an application, take a look at Graphex, a GUI for the BGL, which can read yEd files using this code.
Try this workaround:
https://stackoverflow.com/a/55807107/4761831
I just inherited a class and removed some codes that cause the exception.

boost::filesystem exists() on directory path fails, but is_directory() is ok

I'm getting path to current directory with boost filesystem, then checking if the directory exists.
is_directory() is ok, but exists() fails on the same path, am I missing something?
Example code (boost 1.35):
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
namespace fs = boost::filesystem;
// the path is full path /home/my/somedirectory
fs::path data_dir(fs::current_path());
fs::is_directory(data_dir) // true, directory exists
fs::exists(data_dir) // false
exists(status(data_dir)) // false
EDIT:
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
namespace fs = boost::filesystem;
fs::path data_dir(fs::current_path());
// data_dir == "/home/myusername/proj/test"
if (fs::is_directory(data_dir)) // true - is directory
if (fs::is_directory(fs::status(data_dir))) // true - it is still a directory
Fun part:
if (fs::exists(fs::status(data_dir))) // true - directory exists
if (fs::exists( data_dir )) // true - directory exists
BUT:
if (!fs::exists(fs::status(data_dir))) // false - directory still exists
if (!fs::exists( data_dir )) // true - directory does not exists
The following is from the Boost source code:
inline bool is_directory( file_status f ) { return f.type() == directory_file; }
inline bool exists( file_status f ) { return f.type() != status_unknown && f.type() != file_not_found; }
As you can see, if is_directory returns true then exists must return true as well. Maybe the problem is elsewhere in your code - please post a minimal compilable example that shows the problem.
You may also want to try using the same file_status object for both calls, to see if maybe the output status was changing.

No filenames in pdb program database

I have a .pdb program database from a C++ application compiled in debug on Windows VS2005. I use the DIA SDK to find function names but I can't seem to retrieve the filenames for the symbols.
Is there some switch I need to turn on? Does this work?!
So the answer to this appears to be that you find the line number first and then the source file?!
E.g.
virtual IProgramSymbol^ getSymbolFromAddress(UInt32 address)
{
// Find the symbol with the virtual address we were given
IDiaSymbol ^ sym = nullptr;
m_session->findSymbolByVA( address, SymTagEnum::SymTagFunction, sym );
if (sym != nullptr)
{
// Get source code information via lines numbers. Odd, but this seems to be the way
// to do it.
String ^ srcFile = "unknown";
int line = 0;
UInt64 startAdr = sym->virtualAddress;
// Find line numbers from start_address to start_address+1, which should be 1 symbol!
IDiaEnumLineNumbers ^ lines;
m_session->findLinesByVA(startAdr, 1, lines);
if (lines != nullptr)
{
// get the line number
IDiaLineNumber ^ lnb = lines->Item(0);
line = lnb->lineNumber;
// get the source file from the line number (weird!)
IDiaSourceFile ^ sf = lnb->sourceFile;
if (sf != nullptr)
{
srcFile = sf->fileName;
}
}
return gcnew DiaSymbol(sym, srcFile, line); // found a function
}

Resources