I have been spending the past hour trying to figure out how to display a text document programmatically in c++.
The following is the simple main.cpp code, in which I create a directory "Profiles", and another directory "TestProfile" inside. In Profiles/TestProfile I create a "TestFile" and write "Test data" into it.
#include <iostream>
#include <fstream>
#include <sys/stat.h>
#include "Profile.hpp"
#include <stdlib.h>
using namespace std;
int main(int argc, const char * argv[]) {
ofstream fs;
mkdir("/Users/dario/Desktop/Profiles", S_IRWXU);
mkdir("/Users/dario/Desktop/Profiles/TestProfile", S_IRWXU);
fs.open("/Users/dario/Desktop/Profiles/TestProfile/TestFile");
fs << "Test data\n";
string path = "/Users/dario/Desktop/Profiles/TestProfile/TestFile";
system(path.c_str());
return 0;
}
Everything up until line 30 works as expected. The directories are there, and "TestFile" is present with data written.
There are no errors present when compiling, but ./a.out gives me a permission denied
darios-mbp:FMES dario$ g++ -std=c++2a main.cpp
darios-mbp:FMES dario$ ./a.out
sh: /Users/dario/Desktop/Profiles/TestProfile/TestFile: Permission denied
I tried a few approaches.
First, I checked the permissions of the text file using ls -l,
it returned -rw-r--r--, so I used chmod 755. After that, the file permissions said -rwxr-xr-x. When running the same code, ./a.out returned no permission denied and it seems like it worked, but the text file was not opened.
Secondly, after the first approach didn't work, I deleted the directories and ./a.out to recreate the original permission denied issue.
I was getting permission denied as before, and this time I tried changing the ownership or the directory.
sh: /Users/dario/Desktop/Profiles/TestProfile/TestFile: Permission denied
darios-mbp:FMES dario$ chown -R $USER
/Users/dario/Desktop/Profiles/TestProfile/TestFile
darios-mbp:
The command worked, but running the code still did nothing despite no errors.
I tried chmod 755, but again no file was opened.
On previous attempts to fix this issue, after changing the ownership the same way I just explained, I even had an error where it was trying to run the first word of the textfile as a command
Line 1: Test: command not found
Although I was not able to recreate that while writing this.
Perhaps I am doing something completely wrong, but I looked as much as I could for solutions online before writing this post. None of them seemed to work. Perhaps my situation is unique in some way and someone here could help point me in the right direction. I apologize in advance if my post is in any way not to standard (if so, please let me know how I can improve questions for next time).h
I am running the code on xcode
EDIT
Thanks to #Codo for the answer, the following edit did what I was looking for
string path = "/Users/dario/Desktop/Profiles/TestProfile/TestFile";
string cmd = "open -a TextEdit ";
system(cmd.c_str());
I understand that you want to open the created file with an appropriate application. Let's assume the file is /dir/file.
To open a file from the command line / terminal, you would run:
open /dir/file
Or, if you want a specific applications:
open -a TextEdit /dir/file
Also see The macOS open Command.
If you just run:
/dir/file
you would execute the file. That's probably not what you intended. And execution is only possible if the file meets certain criteria like execution rights and in the case of a shell script an appropriate header.
In C++, the system() function executes a command that would be valid on the command line (in the terminal).
Thus, to fix your program, change the line with system() to:
string cmd = "open -a TextEdit ";
cmd += path;
system(cmd.c_str());
And for your next question: Paste code as text, not as image: Why not upload images of code/errors when asking a question?
Related
This is my first project with Visual Studio Code. When i go to run my "Hello World" project I get this
cd "c:\Users\imaco\Desktop\Cpppractice" && g++ main.cpp -o main && "c:\Users\imaco\Desktop\Cpppractice"main
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: cannot open output file main.exe: Permission denied
collect2.exe: error: ld returned 1 exit status
my code reads
1 #include <iostream>
2
3
4
5 int main()
6 {
7 std:: cout << "Hello World!";
8 }
-I've made sure it isn't running in the background.
-I've closed and reopened the program and ran the code again with same results.
-I've allowed it as an exception in Bit Defender.
Any help would be greatly appreciated!!
I need 50 reputation to comment, otherwise I would have added a comment. I ran into this issue myself and I solved it using this. However, it worked for me:
"cannot open output file main.exe: Permission denied collect2.exe: error: ld returned 1 exit status"
It says that the permission has been denied. This probably means that you have not given execute access to visual studio in a certain folder or the file has execute restrictions. You could probably be storing this file in a folder that has restricted access. There are a couple of options:
You could probably move it to a new folder that does not have any execute access restrictions.
You may have have to change the permission of that folder/file to read, write and execute using admin privileges.
If this does not work, let me know in the comments section, because I faced the same issue of permission denied.
One of the reasons for this error is that your firewall is blocking "collect2.exe" file. In some cases the firewall is disconnected so you might need to connect with it. Hope it helps !
Try to open terminal (Ctrl + `) and type:
g++ main.cpp then
.\a.exe
(assuming the terminal opens up in your working directory)
This usually happens when VS decides to keep a chunk of code running as a separate entity in the background. A way to fix this is that since you are on Windows, I would right-click the taskbar and click on task manager. This will open up all the tasks that are currently running on the computer. Then, search for "Windows console host." You can change the sorting of the list. Once you find it you can click on it and then at the bottom right it will have an "End Task" available for you to click. Click that and then retry again.
You should be good after that, but let me know if you are still having issues.
when this occurs i usually just remove the exe file and build again
Problem: my C++ program cannot write to a file after reboot because it is denied access.
The program is added into the registry at the following location, thus enabling it during start up:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
The following snipper within the code is similar to the one that is causing the problems:
ofstream myfile;
myfile.open ("example.txt", ios:app);
myfile << "Writing this to a file.\n";
myfile.close();
Because this snippet of code runs within a loop the file is repeatedly opened and closed, but when the computer is rebooted the program seems to loose file permissions to it, and .open says it got an Acess Denied error with respect to the file.
What is the problem here? How come the program runs when it is initiated by me without admin rights, but not when Windows initiates it?
As I understand the problem is not in C++ libs but in rights that your application has when windows run it. So, try the following:
1) create shortcut for your exe-file;
2) in HKEY_CURRENT_USER\...\Run change name of application from *.exe to *.lnk (just to run application with help of shortcut);
3) in the shortcut's properties in the Advanced Security Settings section change OWNER to SYSTEM.
perhaps this helps.
"example.txt" is relative to your working directory, which is probably different when run at startup. Add a hardcoded path to test this hypothesis.
I successfully compiled a MUD source code, and it says in the instructions to start up the server using
nohup ./startup &
although when I do this it gives me this error:
$ nohup: ignoring input and appending output to `nohup.out'
nohup: failed to run command `./startup': Permission denied
I have looked all over the internet to find the answer. A few of them said to put my cygwin directory in the root folder (I am using windows 7) and its directory is C:\cygwin
so thats not a problem.. Can anyone help me with this please??
Try chmod +x startup, maybe your startup file is not executable.
From "man nohup":
If the standard output is a terminal, all output written by the named
utility to its standard output shall be appended to the end of the
file nohup.out in the current directory. If nohup.out cannot be
created or opened for appending, the output shall be appended to the
end of the file nohup.out in the directory specified by the HOME
environment variable. If neither file can be created or opened for
appending, utility shall not be invoked. If a file is created, the
file's permission bits shall be set to S_IRUSR | S_IWUSR.
My guess is that since "sh -c" doesn't start a login shell, it is inheriting the environment of the invoking shell, including the HOME environment variable, and is trying to open it there. So I would check the permissions of both your current directory and $HOME. You can try to touch test.txt in current directory or $HOME to see if you can perform that command.
As staticx writes, check the permissions of the directory (and the user) - and the executable.
Instead of using nohup:
check if nohup is needed at all, try ./startup </dev/null >mud.out 2>mud.err &, then close the terminal window and check if it is running
or just run ./startup in a screen session and detach it (<ctrl>+<a>,<d>)
I'm trying to execute a graphviz/dot cmd from within my program,
but I'm still getting the error sh: dot: command not found.
So that's the line that matters:
system("dot -Tpng myfile.txt -o mypic.png");
Executing it on the terminal works pretty well, cause dot is set into my path variable.
Trying to execute the same programmatically ends up in the described error.
Is there any trick using the system cmd where I have to mention my path additionally?
(Btw: I already did include stdlib.h, dunno wether that's important...)
Thx a lot!
You can try something like this:
#include <stdlib.h>
int main()
{
system("PATH=$PATH:<YOUR PATH TO **dot**>;<**dot** and the rest>");
}
as shocking as it seems, this works for me ...
(obviously replace between < > ... )
I am writing a C++ program which has to automatically generate some data to be used by students in an integrated exercise. I have already exported this data to .tex files and would also like the C++ program to be able to compile these tex files automatically.
Usually I would compile tex files from the command line by doing the following:
$ latex file.tex
$ latex file.tex
$ dvipdf file.dvi
So I tried doing the following in my C++ code (directory and filename are both strings):
//Move to the location where I created the files
string mycommand = "cd ";
mycommand += directory;
system(mycommand.c_str());
//Compile latex
mycommand = "latex " + filename + "_main.tex";
system(mycommand.c_str());
system(mycommand.c_str());
//Create .pdf
mycommand = "dvipdf " + filename + "_main.dvi";
system(mycommand.c_str());
Which then produces the following error message on the terminal output:
sh: latex: command not found
sh: latex: command not found
sh: dvipdf: command not found
I have searched this online but I have failed to find a solution for this problem, though I believe it is likely to be something very simple.
I am working on OSX and have the following version of latex installed:
pdfTeX 3.1415926-2.4-1.40.13 (TeX Live 2012)
kpathsea version 6.1.0
All help is greatly appreciated!
First, the path to the programs latex and dvipdf needs to be in your PATH environment variable.
Second, the calls of the shell via system are totally independent (in fact a new instance of the shell is started each time). So if you switch the directory in one, this does not affect the others. Switch instead the current directory of your program via:
chdir(directory.c_str())
You need for this
#include <cunistd>
using namespace std;
at the beginning of the file.
Please note that system calls with command lines depending on input parameters can be easily exploited to run arbitrary commands if the parameters (in your case the filename) are not carefully checked. As you do not have quotes, the program fails if there are e.g. whitespaces in the filename.