on Linux 12.04
I have an executable file located in say:
/a/b/exe
and a config file on
/a/b/config
when doing:
cd /a/b/
./exe
everything's ok and the stat function finds the file config on /a/b/
HOWEVER,when running from root
/a/b/exe
the stat doesn't find the config file
any idea why?
it makes it impossible to run the binary using a script that isn't ran from the folder of the exe.
Edit
The call looks like this:
struct stat stFileInfo;
bool blnReturn;
int intStat;
// Attempt to get the file attributes
intStat = stat(strFilename.c_str(),&stFileInfo);
if(intStat == 0) {
// We were able to get the file attributes
// so the file obviously exists.
blnReturn = true;
} else {
// We were not able to get the file attributes.
// This may mean that we don't have permission to
// access the folder which contains this file. If you
// need to do that level of checking, lookup the
// return values of stat which will give you
// more details on why stat failed.
blnReturn = false;
}
In first case cd ..., run exe you change current working directory before executing the program, in second case you launch exe without changing current working directory, and I think in your program you use a relative path to open your config(for example ./config or just config) and it can't find it from current working directory. easiest workaround is to change working directory at start of your app:
int main(int argc, char** argv) {
std::string s( argv[0] ); // path to the program
std::string::size_type n = s.rfind( '/' );
if( n != std::string::npos ) {
std::system( ("cd " + s.substr(0, n)).c_str() );
}
// rest of your code
}
Related
I'm using tcclib to compile and run C code on the fly in my C++ project.
I'm using the binaries provided here https://bellard.org/tcc/
I then open a vs2019 developer prompt and run both those command
lib /def:libtcc\libtcc.def /out:libtcc.lib
cl /MD examples/libtcc_test.c -I libtcc libtcc.lib
My code builds fine, I'm using this code. This code is similar to the one found in the tcclib example, which is this one : https://repo.or.cz/tinycc.git/blob/HEAD:/tests/libtcc_test.c (this is another repo, but it's the same code.
The code I run is this one. This is inside an extern "C" {}.
int tcc_stuff(int argc, const char** argv) {
TCCState* s;
int i;
int (*func)(int);
s = tcc_new();
if (!s) {
fprintf(stderr, "Could not create tcc state\n");
exit(1);
}
/* if tcclib.h and libtcc1.a are not installed, where can we find them */
for (i = 1; i < argc; ++i) {
const char* a = argv[i];
if (a[0] == '-') {
if (a[1] == 'B')
tcc_set_lib_path(s, a + 2);
else if (a[1] == 'I')
tcc_add_include_path(s, a + 2);
else if (a[1] == 'L')
tcc_add_library_path(s, a + 2);
}
}
/* MUST BE CALLED before any compilation */
tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
{
const char* other_file = ReadFile2(argv[1]);
if (other_file == NULL)
{
printf("invalid filename %s\n", argv[1]);
return 1;
}
if (tcc_compile_string(s, other_file) == -1)
return 1;
}
/* as a test, we add symbols that the compiled program can use.
You may also open a dll with tcc_add_dll() and use symbols from that */
tcc_add_symbol(s, "add", add);
tcc_add_symbol(s, "hello", hello);
/* relocate the code */
if (tcc_relocate(s, TCC_RELOCATE_AUTO) < 0)
return 1;
/* get entry symbol */
func = (int(*)(int))tcc_get_symbol(s, "foo");
if (!func)
return 1;
/* run the code */
msg(func(32));
//msg(func2(4));
/* delete the state */
tcc_delete(s);
return 0;
}
When running my code, TCC had the error
tcc: error: library 'libtcc1-32.a' not found
I fixed it by placing this file in the lib/ directory next to my .exe
I also copied the include/ folder to include stdio.h etc.
My question is: why does it need this file in a lib/ folder, instead of the provided tcclib.dll file? Is it possible to "ship" certain headers like stdio.h?
The question has no answer but 360 views, so I thought I'd reply.
The library doesn't necessarily need to be in that folder. To quote the author's command line docs, which still apply to the library,
-Ldir
Specify an additional static library path for the -l option. The default library paths are /usr/local/lib, /usr/lib and /lib.
I inferred your program to be a modified main() of libtcc_test.c & fixed it to the point of functioning. Then I used VS2022 to retrace your steps, put the .a files into the same folder as my new tests_libtcc_test.exe, then I ran this:
tests_libtcc_test c:/lang/tcc/examples/fib.c -Ic:/lang/tcc/include -L.
The library issue appears if I don't -L anything, and disappears if I include at least the ".".
And of course, you can drop the include folder into your redistributable and include it by default right from the code.
Because the tcc DLL is just another interface to the same compiler, it needs the same things tcc.exe would to build an executable; in this case, it needs the same libraries.
I have recently started working in C++ and came across this situation when I have to create a directory while executing my code. The code is working fine when I have to create a single folder but it fails when I have to create another folder withing this newly created folder.
Suppose, I am in C: and want to store my file in C:/A/B/ .The following piece of code using mkdir() works fine if I have to store my file in C:/A/ but fails when I am adding another folder B.
Following is my code snippet:
#include <sys/stat.h>
#include <string>
using namespace std;
int main()
{
string stringpath = "C:/A/B/";
int status = mkdir(stringpath.c_str(),0777);
if(status!=0)
{
//.....
}
else
{
//....
}
}
Can someone help me in creating this directory where I can have any number of folders inside the parent directory? (P.S:I have added the header files sys/stat.h,iostream and string)
This is how you do it in C++17:
#include <filesystem>
namespace fs = std::filesystem;
fs::create_directories("./a/b/c")
mkdir() creates only the last component of the specified path. In your example, it will create only B. If any of the parent directories do not exist (ie, if A does not exist), the function fails with ENOENT. You need to split up the path and call mkdir() for every intermediate directory in the path, ignoring EEXIST errors as you go.
status = mkdir("C:/A/", 0777);
if ((status < 0) && (errno != EEXIST)) ...
status = mkdir("C:/A/B/", 0777);
if ((status < 0) && (errno != EEXIST)) ...
If you don't want to handle this manually, use a wrapper that handles it for you, such as Boost's create_directories() function:
bool create_directories(const path& p);
bool create_directories(const path& p, system::error_code& ec);
Effects: Establishes the postcondition by calling create_directory() for any element of p that does not exist.
Postcondition: is_directory(p)
Returns: true if a new directory was created, otherwise false.
Throws: As specified in Error reporting.
Complexity: O(n+1)where n is the number of elements of p that do not exist.
You can call the following:
string stringpath = "C:/A/B/";
int status = mkdir(stringpath.c_str(),0777);
If
C:/A/ directory exists. If its not exists, then do the following:
string stringpath = "C:/A/";
int status = mkdir(stringpath.c_str(),0777);
stringpath = "C:/A/B/";
int status = mkdir(stringpath.c_str(),0777);
In C++11 you can use the experimental functios:
#include <experimental/filesystem>
...
std::stringstream bufH;
bufH << dirName << fName;
if (!std::experimental::filesystem::exists(bufH.str()))
{
std::experimental::filesystem::create_directories(bufH.str());
}
Try the octal flag 7777 like this to have all the rights necessary to create this folder.
int status = mkdir(stringpath.c_str(), 7777);
Or do a chmod in the A folder like that :
chmod -r 7777 *
i am writing some functions on c++ for compiler less to css.
i installed nodejs, less.
i created a less file test.less
#color: red;
a{color:#color;}
when i run command on terminal:
lessc test.less test.css
it created a files css with name is test.css, but when i run this command via c++, it return a error. please help me. this is my c++ function:
std::string shell_exec( std::string cmd )
{
std::string result = "";
FILE* pipe = popen(cmd.c_str(), "r");
if (pipe == NULL)
{
return result;
}
char buffer[128];
while(!feof(pipe))
{
if(fgets(buffer, 128, pipe) != NULL)
{
result += buffer;
}
}
pclose(pipe);
return result;
}
shell_exec("lessc test.less test.css");
i got a error:
/usr/bin/env: node: No such file or directory
/usr/bin/node is existed.
================ UPDATE: Fixed==================
Thank you #Bass Jobsen , #Lightness Races in Orbit
i fixed by add absolute path to lessc and nodejs
shell_exec("/usr/bin/node /usr/bin/lessc test.less test.css");
From: https://unix.stackexchange.com/a/29620
The advantage of #!/usr/bin/env python is that it will use whatever
python executable appears first in the user's $PATH.
So you should add node to the $PATH of the user that runs your script, see: https://stackoverflow.com/a/13210246/1596547
Notice that i can not compile your code, but i can when using the following code:
int main()
{
std::string r = shell_exec("lessc test.less test.css");
}
Probably also use using namespace std and string instead of std:string.
I'm working under windows 7 with mingw. I have encountered some weird behaviour with unicode filenames. My program needs to be portable, and I'm using boost::filesystem (v 1.53) to handle the file paths.
This has all been going well, until I needed to open files with unicode filenames.
This is not about the content of the file, but the file's name.
I tried the following: For testing I made a folder named C:\UnicodeTest\вячеслав and I tried creating a file inside of it, by appending the file name test.txt to the boost wpath.
For some reason the creation of the file fails. I'm using boost's fstreams and when I try to open the file, the failbit of the stream is set.
Now the funny thing is, that when I append a foldername to the path instead, a call to create_directories() succeeds and creates the correct directory C:\UnicodeTest\вячеслав\folder.
I really don't understand why it won't work with a file. This is the code I use:
boost::filesystem::wpath path;
// find the folder to test
boost::filesystem::wpath dirPath = "C:\\UnicodeTest";
vector<boost::filesystem::wpath> files;
copy(boost::filesystem::directory_iterator(dirPath), boost::filesystem::directory_iterator(), back_inserter(files));
for(boost::filesystem::wpath &file : files)
{
if(boost::filesystem::is_directory(file))
{
path = file;
break;
}
}
// create a path for the folder
boost::filesystem::wpath folderPath = path / "folder";
// this works just fine
boost::filesystem::create_directories(folderPath);
// create a path for the file
boost::filesystem::wpath filePath = path / "test.txt";
boost::filesystem::ofstream stream;
// this fails
stream.open(filePath);
if(!stream)
{
cout << "failed to open file " << path << endl;
}
else
{
cout << "success" << endl;
}
If I understand the issue correctly, the issue of being unable to create a file directly within C:\UnicodeTest\вячеслав occurs when you do not create the folder directory, as illustrated below.
// create a path for the folder
//boost::filesystem::wpath folderPath = path / "folder";
// this works just fine
//boost::filesystem::create_directories(folderPath);
// create a path for the file
boost::filesystem::wpath filePath = path / "test.txt";
I was able to get this to work by making the filename a wchar_t string:
// create a path for the file
boost::filesystem::wpath filePath = path / L"test.txt";
I am working on a mini-shell, and am trying to set the execution path dynamically.
I am using setvar() to set the PATH and when I check it with getvar() it reads the new PATH.
Here are the two things I tried to execute:
1. I change the PATH to /bin which I know contains most system functions, but no programs can work. I can also verify that the path has been set in the environment. I execute the commands using execvp()
2. I then used extern char** environ to get the environment and pass it into execvpe() but it still doesn't work.
I solved this by using istringstream to manually search the PATH and then use that to execute the process:
string dir;
string path = get_var("PATH");
istringstream search(path);
while(search.good()) {
getline(search, dir, ':');
if(dir != "") {
struct stat st;
if(dir[dir.length()] != '/') dir.append("/");
string file = dir + cmdArg[0];
//is file in dir?
if(stat(file.c_str(), &st) == 0) {
execvp(file.c_str(), cmdArg);
}
}
}