freopen() doesn't work on mac - c++

I am trying to run a code with freopen() on mac os,
but it doesn't print any output in the specified file.
although, it works perfectly on windows.
I am using the X-Code Editor and the input and the output files are in the same path as the cpp file
#include <cstdio>
int main(){
freopen("input.in","r",stdin);
freopen("output.out","w",stdout);
int x;
scanf("%d",&x);
printf("%d\n",x);
return 0;
}

That's because the working directory of your executable is not the directory where you have your .cpp files.
You may point to your files with absolute paths, ex. /Users/omar/Documents/input.in
or change the working directory from xcode settings (see Change the working directory in Xcode )

I personally tried changing the working directory, but it still didn't work...
Later I find out that if you compile your c++ file using Terminal, there would be no trouble at all!
To compile c++ using Terminal, type in these commands:
cd yourFileDirectory
g++ -o yourFileName yourFileName.cpp (this will compile your code)
./yourFileName (and this will run the code successfully!)

Related

Generate preprocesed file ( .i ) in code blocks

I am following The Cherno C++ series and in this video he is talking about generating .i files. I am an Ubuntu [20.04] user and am making my projects on Code::Blocks. Does any one know how to generate .i files in Code::Blocks?
actually you can't directly genrate a preprocessor file in Code::Blocks
as far as my knowledge go. Because I am also following the same series and I also had this problem { i am also using C::b }, so what you can do is in ubuntu terminal go to that file location by using cd command and then use
gcc -E FileName.c -o FileName.i
command this will genrate the preprocessor file.

Problem with filestream path in C++ when copying files

Brace with me here. I'm trying to make a few simple, but useful C++ console apps that I want to run by starting them straight from cmd (like DiskPart for example). I have a finished product, compiled by gcc through VS Code powershell. The idea is: I have a main.exe and a data file stored in "veco/data.txt" next to the executable. The code works perfectly well when started from its folder where it was compiled, but when I try to copy it to WindowsApps folder (to be able to start it by typing its name in cmd) it just doesn't work...
Yes I did copy the folder too, I've tried to run it from powershell and I get 0 crash msgs...
Here's the part where I interact with the text file:
string s = _pathToExe + "veco\\data.txt";
ifstream is(s);
//i do stuff here
is.close();
where _pathToExe is path to the executable, without the actual name of the executable. ifstream is(s) seems to be the crashing point.
I compiled the code using two commands:
g++ -c <all .cpps>
g++ -o main.exe <all objs>
Can I make this work somehow? Any other suggestions are welcome too.
Note: I've tried copying to other locations, doesn't work there either.

how do I load a file for c++ on mac

I am trying to load my file with C++ using ifstream, however it just wouldn't work. I use Atom with Xcode as compiler on my Mac.
This pops up:
dyn3180-214:~ joshua$ /var/folders/y6/jrfdjlsx0nqcxyfvsrfw6bnw0000gn/T/excersice ; exit;
file was not opened correctly
logout
#include <iostream>
#include <fstream>
#include <cstdlib>
int main(){
std::ifstream infile;
infile.open("numbers.txt");
if(!infile.is_open()){
std::cout<<"file was not opened correctly"<<std::endl;
exit(EXIT_FAILURE);
}
int n;
while(infile>>n){
std::cout<<n<<std::endl;
}
return 0;
}
Read how to debug small programs and also the documentation of GDB (or of whatever debugger you have on your machine).
Compile your program (that is the C++ file, let's name it josh.cc, shown in your question) with all warnings and debug info. I recommend to compile it on the command line with g++ -Wall -Wextra -g josh.cc -o joshprog (read how to invoke GCC for details) then to debug it with gdb ./joshprog and to run it in a terminal as ./joshprog.
The point is that your IDE (Atom + XCode) is not helping you. It hides you important details (see this answer, it also works for MacOSX or other Unix systems). That is why I strongly recommend compiling (and running, and debugging) your code with explicit commands that you are typing in a terminal emulator for your shell and understanding (so read the documentation of every command that you are using). Once you are fluent with compilation on Unix systems, you might eventually switch to an IDE (but you need to understand what your IDE is doing on your behalf, and what commands it is running).
You could add into your code something displaying the current working directory by using getcwd (which requires #include <unistd.h> on POSIX system), maybe something like
char mycwdbuf[80];
memset (mycwdbuf, 0, sizeof(mycwdbuf));
if (getcwd(mycwdbuf, sizeof(mycwdbuf)-1) != NULL)
std::cout << "current directory is " << mycwdbuf << std::endl;
By doing that, you'll probably understand how is your program started and in which working directory. I guess that it was not started in the working directory that you wanted it to.
In Xcode, select the project navigator, then click on your project. This will open the project editor. Select the Build Phases tab. Open the dropdown for Copy Files. Set Destination to Products Directory. Add a Subpath if you have to. Drag the necessary files into the project editor or add them via +.
Example: During the build phase, project files associated with the target will be copied to the designated subpath in the directory within the Products directory.
I think, Xcode generating the .o (object file ) file in different directory, and your .txt is present in different directory. I do code in Xcode, it always generate the .o file in different directory.

Error while compiling my c++ program

I am a c++ beginner and after reading many articles on good ways to learn programming, I have found that its a good practice to learn programming through using command line interface than through IDE's. So therefore I am trying to learn c++ through command line interface. I am following my first tutorial of a "hello world" program. I am using MinGW compiler to compile my code. As I try to compile my code in the windows command prompt, I am getting an error. I have searched throughout the internet but can't seem to find an answer for this problem. The command I use to compile my code is "g++ Motto.cpp -o Motto.exe" and I get the problem "g++:error:CreateProcess:No such file or directory". I have checked for the path environment variable and it has the MinGW path. I have also checked the MinGW folder and found that all the executives needed are installed. Please help me fix the problem.
Here is the code:
#include <iostream>
int main()
{
std::cout << "Hello world\n";
return 0;
}
That usually means the g++ cannot find some executables that it needs to run during the compilation. Especially with MinGW the installation can be little tricky.
Make sure the paths to the MinGW installation is in your PATH environment variable (echo %PATH%) and also try to restart the computer.
If you installed manually and not with the MinGW installer (mingw-get), make sure you have downloaded and installed all the prerequisities (core, c++, binutils, runtime, etc.).
The g++ --version only prints the version, so it does not need to call another executables which the compilation does (like cc/c++, ar, etc).
Check the bin folder inside your MinGW installation directory, if you have at least those executables there: cc, c++, c++filt, ld (and others like ar, as).
Also, check {MinGWDir}\libexec\gcc\mingw32{version} if it contains cc1, cc1plus, collect2.
Try running "make $file-you-want", or like #FCo said, "g++ -o Motto Motto.cpp", The error means that you're passing it an invalid filename to compile, or you're not in the proper directory. Make sure you have the file you want to compile in your working directory, either by typing "ls" or "dir" depending on the system you're using.
Information that would help answer this question:
What you're doing to cause the error (how are you running g++?)
What OS/Environment you're running on

How can I compile and run C/C++ code in a Unix console or Mac terminal?

How can I compile/run C or C++ code in a Unix console or a Mac terminal?
If it is a simple single-source program,
make foo
where the source file is foo.c, foo.cpp, etc., you don’t even need a makefile. Make has enough built-in rules to build your source file into an executable of the same name, minus the extension.
Running the executable just built is the same as running any program - but you will most often need to specify the path to the executable as the shell will only search what is in $PATH to find executables, and most often that does not include the current directory (.).
So to run the built executable foo:
./foo
gcc main.cpp -o main.out
./main.out
This is the command that works on all Unix machines... I use it on Linux/Ubuntu, but it works in OS X as well. Type the following command in Terminal.app.
g++ -o lab21 iterative.cpp
-o is the letter O, not zero
lab21 will be your executable file
iterative.cpp is your C++ file
After you run that command, type the following in the terminal to run your program:
./lab21
Two steps for me:
First:
make foo
Then:
./foo
All application execution in a Unix (Linux, Mac OS X, AIX, etc.) environment depends on the executable search path.
You can display this path in the terminal with this command:
echo $PATH
On Mac OS X (by default) this will display the following colon separated search path:
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
So any executable in the listed directories can by run just by typing in their name. For example:
cat mytextfile.txt
This runs /bin/cat and displays mytextfile.txt to the terminal.
To run any other command that is not in the executable search path requires that you qualify the path to the executable. So say I had an executable called MyProgram in my home directory on Mac OS X I can fully qualify it like so:
/Users/oliver/MyProgram
If you are in a location that is near the program you wished to execute you can qualify the name with a partial path. For example, if MyProgram was in the directory /Users/oliver/MyProject I and I was in my home directory I can qualify the executable name like this, and have it execute:
MyProject/MyProgram
Or say I was in the directory /Users/oliver/MyProject2 and I wanted to execute /Users/oliver/MyProject/MyProgram I can use a relative path like this, to execute it:
../MyProject/MyProgram
Similarly if I am in the same directory as MyProgram I need to use a "current directory" relative path. The current directory you are in is the period character followed by a slash. For example:
./MyProgram
To determine which directory you are currently in use the pwd command.
If you are commonly putting programs in a place on your hard disk that you wish to run without having to qualify their names. For example, if you have a "bin" directory in your home directory for regularly used shell scripts of other programs it may be wise to alter your executable search path.
This can be does easily by either creating or editing the existing .bash_profile file in your home directory and adding the lines:
#!/bin/sh
export PATH=$PATH:~/bin
Here the tilde (~) character is being used as a shortcut for /Users/oliver. Also note that the hash bang (#!) line needs to be the first line of the file (if it doesn't already exist). Note also that this technique requires that your login shell be bash (the default on Mac OS X and most Linux distributions). Also note that if you want your programs installed in ~/bin to be used in preference to system executables your should reorder the export statement as follows:
export PATH=~/bin:$PATH
Do all of this in "Terminal".
To use the G++ compiler, you need to do this:
Navigate to the directory in which you stored the *.cpp file.
cd ~/programs/myprograms/
(the ~ is a shortcut for your home, i.e. /Users/Ryan/programs/myprograms/, replace with the location you actually used.)
Compile it
g++ input.cpp -o output.bin (output.bin can be anything with any extension, really. Extension .bin is just common on Unix.)
There should be nothing returned if it was successful, and that is okay. Generally you get returns on failures.
However, if you type ls, you will see the list of files in the same directory. For example, you would see the other folders, input.cpp and output.bin
From inside the directory, now execute it with ./outbut.bin
A compact way to go about doing that could be:
make foo && ./$_
It is nice to have a one-liner so you can just rerun your executable again easily.
Assuming the current directory is not in the path, the syntax is ./[name of the program].
For example ./a.out
To compile C or C++ programs, there is a common command:
make filename
./filename
make will build your source file into an executable file with the same name. But if you want to use the standard way, You could use the gcc compiler to build C programs and g++ for C++.
For C:
gcc filename.c
./a.out
For C++:
g++ filename.cpp
./a.out
Add the following to get the best warnings, and you will not regret it. If you can, compile using WISE (warning is error).
- Wall -pedantic -Weffc++ -Werror
Step 1 - create a cpp file using the command
touch test.cpp
Step 2 - Run this command
g++ test.cpp
Step 3 - Run your cpp file
./a.out
I am on a new MacBook Pro with the Apple M1 Pro chip. I have my Xcode installed - both IDE and command line tools. This is how it worked for me:
g++ one.cpp -o one
./one
Use a makefile. Even for very small (= one-file) projects, the effort is probably worth it because you can have several sets of compiler settings to test things. Debugging and deployment works much easier this way.
Read the make manual. It seems quite long at first glance, but most sections you can just skim over. All in all, it took me a few hours and made me much more productive.
I found this link with directions:
http://www.wesg.ca/2007/11/how-to-write-and-compile-c-programs-on-mac-os-x/
Basically you do:
gcc hello.c
./a.out (or with the output file of the first command)
In order to compile and run C++ source code from a Mac terminal, one needs to do the following:
If the path of .cpp file is somePath/fileName.cpp, first go the directory with path somePath
To compile fileName.cpp, type c++ fileName.cpp -o fileName
To run the program, type ./fileName
Just enter in the directory in which your .c/.cpp file is.
For compiling and running C code.
gcc filename.c
./a.out filename.c
For compiling and running C++ code.
g++ filename.cpp
./a.out filename.cpp
You need to go into the folder where you have saved your file.
To compile the code: gcc fileName
You can also use the g++ fileName
This will compile your code and create a binary.
Now look for the binary in the same folder and run it.
For running C++ files, run the below command, assuming the file name is "main.cpp".
Compile to make an object file from C++ file.
g++ -c main.cpp -o main.o
Since #include <conio.h> is not supported on macOS, we should use its alternative which is supported on Mac. That is #include <curses.h>. Now the object file needs to be converted to an executable file. To use file curses.h, we have to use library -lcurses.
g++ -o main main.o -lcurses
Now run the executable.
./main
Running a .C file using the terminal is a two-step process.
The first step is to type gcc in the terminal and drop the .C file to the terminal, and then press Enter:
gcc /Desktop/test.c
In the second step, run the following command:
~/a.out