C++ make folder inside Program files - c++

I am trying to create a directory inside program files, but my code failed. I can make folder directly on the root, so this is very strange I think.
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <direct.h> // _mkdir
int _tmain(int argc, _TCHAR* argv[])
{
// Make directory
if(_mkdir("C:\\Program Files\\MyProgram") == 0 ){
cout << "Folder created" << endl;
}
else{
cout << "Folder creation failed" << endl;
}
// Pause program
system("PAUSE");
return 0;
}
Edit:
Thank you. I understand that c:\Program files\MyProgram is only for install files, but where should I put save files? Example save files for a C++ game. Should they be stored in "C:\Users\Username\Documents\MyProgram"?

The proper folder name to write depends on version and localization.
A simple way to get that name is to search for the APPDATA environment variable.
See here to get an environment variable, and here about the recognized environment variables and meanings.

Related

How to copy files to another directory using c++ filesystem library

I'm attempting to automate some image processing, and once I have processed an image I would like to move it to another directory.
I have tried using std::experimental::filesystem::copy and std::experimental::filesystem::copy_file, but I get an error of "Could not copy file: copy_file(p1, p2, options): invalid arguments: operation not permitted"
#include <filesystem>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char* argv[]) {
if (argc < 2) {
cout << "no directory specified" << endl;
return 0;
}
experimental::filesystem::path inputPath(argv[1]);
experimental::filesystem::path
for (auto const & entry : experimental::filesystem::directory_iterator(inputPath)) {
string src = entry.path().string();
experimental::filesystem::path dest("C:\\Users\\Keelan\\Desktop\\MatchTest\\IMG_Copy\\"+ entry.path().filename().string());
cout << entry.path() << endl;
cout << "Copying " << src << " to " << dest << endl;
experimental::filesystem::copy_file(entry.path(), dest, experimental::filesystem::copy_options::none);
}
return 0;
}
I have so far had no success using the either of these copy functions. I have seen other solutions involving redirecting file-streams but I don't think this is appropriate given I will be processing files on demand and need to minimise response time.
EDIT: the folder I'm copying to exists and all users have read/write permissions
EDIT 2: I deleted and recreated the folder and the problem is fixed, not sure of the reason why
There are 2 potential issues here:
Since you use experimental::filesystem::copy_options::none you will get an exception if the file already exists - see the paragraph "Otherwise, if the destination file already exists" here
If the source folder contains subfolders with files, the directory_iterator will iterate them as well, but if you attempt to copy a file nested deeper, you need to create the target directory hierarchy as well.

How to navigate through directories using c++ to create a file explorer

I'm trying to create a file explorer in C++ using Ncurses for my class. Currently I'm trying to find a way to navigate through the file system and find out if 'x' is file/directory and act accordingly.
The problem is I can't find a way to navigate through directories they way I'd like. For example, in the code below I start at "." and then read it while saving some info of said directory and its files. But I'd like to define the cwd to "/home" everytime the program runs and then go from there exploring whatever the user wants like:
display /home -> user selects /folder1 -> display /folder1 -> user selects /documents -> ...
I've read about scripts and tried to create a "cd /home" script but it doesn't work. Somewhere I read that the execve() function might work, but I don't understand it. I've got a feeling that I'm overthinking this, and frankly I'm stuck.
edit: In essence I'd like to find: How to make it so that my program starts at "path" so that when I call getcwd() it returns "path" and not the actual path of the program.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <dirent.h>
#include <string.h>
#include <linux/limits.h>
#include <iostream>
#include "contenido.cpp"
using namespace std;
//Inicia main
int main(int argc, char const *argv[]) {
DIR *dir; //dir is directory to open
struct dirent *sd;
struct stat buf; //buf will give us stat() atributes from 'x' file.
char currentpath[FILENAME_MAX]; //currentpath
contenido dcont;
//system (". /home/rodrigo/Documentos/Atom/Ncurses/Proyecto/beta/prueba.sh");
if((dir = opendir(".")) == NULL){ /*Opens directory*/
return errno;
}
if(getcwd(currentpath, FILENAME_MAX) == NULL){
return errno;
}
while ((sd= readdir(dir)) != NULL){ /*starts directory stream*/
if(strcmp(sd -> d_name,".")==0 || strcmp(sd -> d_name,"..") ==0){
continue;
}
//Gets cwd, then adds /filename to it and sends it to a linked list 'dcont'. Resets currentpath to cwd
//afterwards.
getcwd(currentpath, FILENAME_MAX);
strcat(currentpath, "/");
strcat(currentpath, sd->d_name);
string prueba(currentpath);
//std::cout << currentpath << '\n';
dcont.crearnodo(prueba);
if(stat(currentpath, &buf) == -1){
cout << currentpath << "\n";
perror("hey");
return errno;
}
getcwd(currentpath, FILENAME_MAX);
//Prints Files and Directories. If Directory prints "it's directory", else prints "file info".
if (S_ISDIR(buf.st_mode)) {
cout << sd->d_name << "\n";
cout << "ES DIRECTORIO\n";
}else
cout << sd->d_name << "\n";
cout <<"Su tamaƱo es: " << (int)buf.st_size << "\n";
//system("ls");
}
closedir(dir);
dcont.mostrardircont(); //prints contents of the linked list (position in list and path of file).
return 0;
}
To change your current working directory use chdir
If you want to change your cwd to "/home"
chdir("/home");
The chdir only persists within the program that did it (or subprocesses). It won't cause the shell to change. There's an application (wcd) which does something like what you're trying, which combines the navigation with a shell script.

Why doesn't this open the file in the directory of the program?

I have this short program:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
int main (int argc, char * argv[]) {
std::string homedir = std::getenv("HOME");
std::string filename = argc > 1 ? argv[1] : (homedir + "/" + "file");
std::cout << homedir << std::endl;
std::cout << filename << std::endl;
std::fstream file;
file.open(filename, std::ios::out);
file << "Yo yo waddup" << std::endl;
file.close();
return 0;
}
When I supply no arguments, it opens a file in the users home directory. That of course makes sense. But when I run it from a different directory like this:
$ ./folder/hometest examplefile
The program creates "examplefile" in my current directory instead of the directory where the program is.
Why exactly is this happening?
Why exactly is this happening?
The program is behaving just as expected.
The file is opened relative to the current work directory, not where the executable is located.
If it didn't work that way,
All your programs will have to work with absolute paths, or
The location of the program will be flooded with files. First, that might not be possible because of permissions issue. Second, in a multi-user system, users will end up trying to create the same file names/directories.
Neither of the above is desirable.

Gnuplot & C++: Can't find gnuplot neither in PATH nor in "

I am trying to use Gnuplot on Windows with gnuplot_i.hpp. When I type "gnuplot" into cmd everthing works, so the PATH variable should be set correctly. This is my code:
#include <iostream>
#include "gnuplot_i.hpp"
using std::cout;
using std::endl;
int main(int argc, char* argv[]) {
try {
Gnuplot g1("lines");
} catch (GnuplotException ge) {
cout << ge.what() << endl;
}
return 0;
}
The output is Can't find gnuplot neither in PATH nor in "C:/program files/gnuplot/bin" .
When I add the line
Gnuplot::set_GNUPlotPath("C:/gnuplot/bin/");
it just changes to Can't find gnuplot neither in PATH nor in "".
What am I doing wrong here?
Found the answer myself: For some reason gnuplot_i.hpp expects your exe to be called pgnuplot.exe instead of gnuplot.exe ... Now everything works.

C++ - stat(), access() not working under gnu gcc

I've got a pretty basic console program here, to determine if a folder or file exists or not using stat:
#include <iostream>
#include <sys/stat.h>
using namespace std;
int main() {
char path[] = "myfolder/";
struct stat status;
if(stat(path,&status)==0) { cout << "Folder found." << endl; }
else { cout << "Can't find folder." << endl; } //Doesn't exist
cin.get();
return 0;
}
I have also tried the access version:
#include <iostream>
#include <io.h>
using namespace std;
int main() {
char path[] = "myfolder/";
if(access(path,0)==0) { cout << "Folder found." << endl; }
else { cout << "Can't find folder." << endl; } //Doesn't exist
cin.get();
return 0;
}
Neither of them find my folder (which is right there in the same directory as the program). These worked on my last compiler (the default one with DevCpp). I switched to CodeBlocks and am compiling with Gnu GCC now, if that helps. I'm sure it's a quick fix - can someone help out?
(Obviously I'm a noob at this so if you need any other information I've left out please let me know).
UPDATE
The problem was with the base directory. The updated, working program is as follows:
#include <iostream>
#include <sys/stat.h>
using namespace std;
int main() {
cout << "Current directory: " << system("cd") << endl;
char path[] = "./bin/Release/myfolder";
struct stat status;
if(stat(path,&status)==0) { cout << "Directory found." << endl; }
else { cout << "Can't find directory." << endl; } //Doesn't exist
cin.get();
return 0;
}
ANOTHER UPDATE
Turns out that a trailing backslash on the path is big trouble.
Right before your stat call, insert the code:
system("pwd"); // for UNIXy systems
system("cd"); // for Windowsy systems
(or equivalent) to check your current directory. I think you'll find it's not what you think.
Alternatively, run the executable from the command line where you know what directory you're in. IDEs will frequently run your executable from a directory you may not expect.
Or, use the full path name so that it doesn't matter which directory you're in.
For what it's worth, your first code segment works perfectly (gcc under Ubuntu 10):
pax$ ls my*
ls: cannot access my*: No such file or directory
pax$ ./qq
Cannot find folder.
pax$ mkdir myfolder
pax$ ll -d my*
drwxr-xr-x 2 pax pax 4096 2010-12-14 09:33 myfolder/
pax$ ./qq
Folder found.
Are you sure that the current directory of your running program is what you expect it to be? Try changing path to an absolute pathname to see if that helps.
Check your PWD when you running your program. This problem is not caused by compiler. You DevCpp may set a working directory for your program automatically.
You can find out why stat() failed (which is a C function, not C++, by the way), by checking errno:
#include <cerrno>
...
if (stat(path,&status) != 0)
{
std::cout << "stat() failed:" << std::strerror(errno) << endl;
}