I am using XCode, and here is a c++ code in XCode
std::fstream stream("templates.Xml", std::ios::binary | std::ios::in);
if(!stream) return false;
I put the Xml file in the folder that contain the ".xcodeproj", and I put it in the folder that contains ".app" but the stream always return false, why?
It looks like you are trying to open the file from the wrong directory.
"templates.Xml" is saved in the bundle- is not saved in the documents directory. By default, if you open "./filename", this actually points to:
/Users/arinmorf/Library/Application Support/iPhone Simulator/7.0.3/Applications/246E91F9-FAB2-4A46-B1F1-855B5363F24D/Documents/
Where arinmorf would be your username and the long hex string is randomly generated every time you install the app on the simulator.
The templates.xml file would be found in:
/Users/arinmorf/Library/Application Support/iPhone Simulator/7.0.3/Applications/246E91F9-FAB2-4A46-B1F1-855B5363F24D/iFly.app/templates.xml
iFly.app is the name of my app, yours would be "T". BUT you can't use the absolute path in your project, because of the randomly generated string, you need to use the NSBundle or CFBundleRef.
In objective-C, you would use:
filePath = [[NSBundle mainBundle] pathForResource:#"templates" ofType:#"xml"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
In C++ it looks like:
CFURLRef fileURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("templates"), CFSTR("xml"), NULL);
CFStringRef filePath = CFURLCopyFileSystemPath(fileURL, kCFURLPOSIXPathStyle);
CFStringEncoding encodingMethod = CFStringGetSystemEncoding();
const char *path = CFStringGetCStringPtr(filePath, encodingMethod);
FILE* f = fopen(path, "r");
(Credit to Chris Frederick at https://stackoverflow.com/a/8768366/2070758 for C++ version)
Yes, I solved the problem in two ways either depending on Main Bundle, or create custom bundle and use it.
Related
I wrote a daemon service program and I want to open a file in /home/user path while the service is active. But I don't want to open file as root. The first thing I tried for this was to get the user name with the getenv("USER") function, keep it in a string, and then open a txt file with this string path. But after daemonize the program getenv function caused core dump.
int main(){
make_daemon();
const char *userName = "USER";
const char *homePath = "/home/";
const char *env_p = getenv(userName); //Core dump!
std::string m_filePath = homePath;
m_filePath += env_p;
m_filePath += "/test.txt"; // "/home/<user>/test.txt"
//open filePath
//some stuff...
}
I can probably solve this problem by running the service as root and creating a text file somewhere in the /usr/local/ path, but I want to create the text file with the user, not root. Is it possible or is there any other way to do this?
Using VC++, how can I remove the extension from the following file path and change it to a new extension(using strings):
CString path(_T(m_DirTree.GetCurrentDir())); // copy file path to variable 'path' of type CString
//Add code here....
The path to the file in question is L:\PowerStar 5 Demo II\Programs\Demo\Programs\33100.PRG and I would like to change the file extension to 33100.CRC. Is there some way I could use _splitpath to change the file extension to .CRC? This path is one of many which can be selected via a directory tree that is passed to variable path and I am just using this particular path as an example. So I cannot alter it as below:
CString path(_T("L:\PowerStar 5 Demo II\Programs\Demo\Programs\33100.CRC"));
Is it possible to concatenate the strings so I can open without getting an exception?
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
// Split path to isolate file extension(.prg) for if statement
_splitpath(m_DirTree.GetCurrentDir(), drive, dir, fname, ext);
CString crcFile;
crcFile = strcat(fname,".CRC"); // concatenate chars to point to .CRC file of same name
FILE *cr = fopen(fname, "r"); // Handle to the file in question
The above code throws an unhandled exception.
Try using the Shell API function PathRenameExtension. Or if you want the buffer management handled for you CPathT::RenameExtension, for example:
CPath path(_T("L:\\PowerStar 5 Demo II\\Programs\\Demo\\Programs\\33100.PRG"));
path.RenameExtension(_T(".CRC"));
CString modifiedPath = path;
CString has 2 methods, which might help you.
ReverseFind() and Left()
CString filenameWithoutExtension = path.Left(path.ReverseFind(_T('.')));
Then you can add your new file extension (e.g. ".exe") at the end of the new string.
path = filenameWithoutExtension + _T(".exe");
I have kept the Content.xml in the same folder where my app.exe exists.
But open call returns false ?
What should be the exact path for the file ?
I do not want to give the complete path for the file but want my code to be path independent "means file which i want to read should be in same folder where my exe is lying"
#define FILE_NAME "Content.xml"
QString xmlFileName(FILE_NAME);
xmlFile.setFileName(xmlFileName);
if ( ! xmlFile.open(QIODevice::ReadOnly|QIODevice::Text) )
{
QMessageBox* msgBox = new QMessageBox();
msgBox->setText("File Not Found !!");
msgBox->setWindowFlags(Qt::WindowStaysOnTopHint);
msgBox->exec();
}
Try to open file with full path like:
xmlFile.setFileName(QCoreApplication::applicationDirPath() + QLatin1Char('/') + xmlFileName);
If you run your code with the run button from Qt Creator, the Content.xml needs to be in the same folder as your code is.
I would like to execute the Applescript command tell application "Finder" to open POSIX file */path/to/somefilename* from a C++ program. It looks like I might want to use OSACompileExecute, but I haven't been able to find an example of how to use it. I keep finding examples of how to use the OSACompile Terminal command. Can someone provide an example or a link to an example?
Ok, the trick was to not bother trying to compile and execute the Applescript but to simply use the osascript system command:
sprintf(cmd, "osascript -e 'tell app \"Finder\" to open POSIX file \"%s/%s\"'", getcwd(path, MAXPATHLEN), file);
system(cmd);
path and file are both char[] variables.
I got the clue from this excerpt from Applescript: The Definitive Guide.
Here's an example C function for reading a Get Info comment from the finder using AppleScript.
You could modify it for what you want.
NSString * readFinderCommentsForFile(NSString * theFile){
/* Need to use AppleScript to read or write Finder Get Info Comments */
/* Convert POSIX file path to hfs path */
NSURL * urlWithPOSIXPath = [NSURL fileURLWithPath:theFile];
NSString * hfsStylePathString =
(__bridge_transfer NSString *)CFURLCopyFileSystemPath((__bridge CFURLRef) urlWithPOSIXPath, kCFURLHFSPathStyle);
/* Build an AppleScript string */
NSString *appleScriptString = #"tell application \"Finder\"\r get comment of file ";
appleScriptString = [appleScriptString stringByAppendingString:#"\""];
appleScriptString = [appleScriptString stringByAppendingString:hfsStylePathString];
appleScriptString = [appleScriptString stringByAppendingString:#"\""];
appleScriptString = [appleScriptString stringByAppendingString:#"\r end tell\r"];
NSString *finderComment;
NSAppleScript *theScript = [[NSAppleScript alloc] initWithSource:appleScriptString];
NSDictionary *theError = nil;
finderComment = [[theScript executeAndReturnError: &theError] stringValue];
NSLog(#"Finder comment is %#.\n", finderComment);
return finderComment;
How I can get actual folder path where my program is without my exe file name in C++?
The following function will give you the application path:
::GetModuleFileName(NULL, szAppPath, MAX_PATH);
Now to extract the folder, you need to find the last backslash:
char szApplicationPath[MAX_PATH] = "";
::GetModuleFileName(NULL, szApplicationPath, MAX_PATH);
//Get the folder part
CString strApplicationFolder;
strApplicationFolder = szApplicationPath;
strApplicationFolder = strApplicationFolder.Left(strApplicationFolder.ReverseFind("\\"));