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

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.

Related

Running C++ file on Terminal in Ubuntu

I'm new to C++.
I've created a C++ file with gedit in Ubuntu. But when I tried to run it on terminal, it says
no such file or directory
When I typed ls on Terminal, it shows that the c++ file was not created at all.
Where did I go wrong?
saved a file with .cpp with gedit on my desktop.
Went to terminal and typed something like g++ -o test file name.cpp.
I was then shown an error message of “no such file or directory”.
This is my code:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World\n";
return 0;
}
First you have to find the directory where you saved the source file from gedit. File->Save As is one place which shows the directory, and there probably is also some "file properties" action in that menu which also shows the path. In command line use cd to move to that directory before running your compilation command.
You can use ls to see if the directory contains the files you expect, as you have done. pwd is useful for showing the full path of your current working directory. In general, it would be very useful if you did a Linux terminal tutorial or two, to get the hang of working on unix terminal command line.
Then it looks like you have spaces in your file name here: g++ -o test file name.cpp
It is a bit unclear which is which, but I presume you want this:
g++ -o test 'file name.cpp'
In unixy terminals, the shell (you probably have bash) is responsible for splitting the command line arguments, and this by default happens at whitespaces. If you have white space in single argument (like the file name here), you have to make it so that shell doesn't split that argument into two. There are several ways to do it, single quotes like above is just one, but it is a broad subject and way beyond this answer.

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

freopen() doesn't work on mac

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!)

New to Xcode can't open files in c++?

I've been using windows in a class I've been taking but I am trying to run a basic code to figure out how to open/close/input/output from files on Xcode and the code I usually use on visual studios isn't working any idea why? thanks!
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream fin;
ofstream fout;
string input;
fin.open("inputFile.txt");
if(fin.fail())
cout << "File failed to open." << endl;
fin >> input;
fout.open("outputFile.txt");
fout << input;
}
Put your .txt files in the same directory where your main.cpp file is (or anywhere you like).
In Xcode go to Product > Scheme > Edit Scheme > Run (on the left) > Options (middle top)
Down under Options for "Working Directory" check “Use custom working directory” and set it to the directory where you .txt files are located.
To work with the files, you will have to specify just file names, e.g. in_file.open("inputFile.txt"); no path is necessary.
Here's a completely different approach: Have Xcode copy the input file for you.
Select your project in Xcode
Select Build Phases
Click the '+' button to create a new Build Phase
Select New Copy Files Build Phase
Select Products Directory
Click the '+' button to add your file
Click Add Other
Select your input file and click Open
Check the Copy items… checkbox and click Finish
Now every time you build your project, the input file will be copied to the same folder as the executable no matter where it is built. Of course, to see the output file, you'll still need to find the executable in Finder.
The answers don't really explain the problem so I thought I'd do that.
When you pass a relative path like "inputFile.txt" to file APIs, it's treated as relative to the working directory when the program is executed. This is the same as the 'working directory' when you use cmd.exe or Terminal.app or command lines in general. The Unix command pwd ("print working directory") displays the current working directory. On Windows running the command cd with no arguments performs the same function. (On Unix running cd with no arguments will change the working directory to the user's home directory.)
When you run a program from the command line, the command line shell sets the program's working directory. When you run a program from within an IDE, the IDE sets the working directory. Since, unlike on a command line, there's no obvious answer for what the IDE should set as the working directory, Visual Studio and Xcode set the working directory to different locations by default: Visual Studio sets the working directory to $(ProjectDir), the directory containing the Visual Studio project file; Xcode sets the working directory to the build products directory, i.e. the location the executable was written to.
Some possible solutions to your problem are:
Do not use a relative path, and therefore don't depend on the working directory. This isn't much help in making the program more portable, because the absolute paths will also differ between platforms, and so you will still have to 'configure' the program for each platform. In fact using an absolute path is worse, because it means your source code must differ, whereas it would be better to keep that difference confined to each platform's build configuration.
Configure the IDE to use your desired working directory. Visual Studio can be configured by right clicking the project, selecting Configuration Properties > Debugging > Working Directory, and setting the working directory to the desired path (potentially using Visual Studio build variables).
nepete's answer describes how to configure the working directly set by Xcode.
Configure the IDE's build process to copy your data files to an appropriate location. In Visual Studio you would do this in a C++ project by configuring the project's Properties > Configuration Properties > Build Events.
SSteve's answer covers how to configure additional build steps in Xcode.
I'm guessing you have inputFile.txt in the folder that contains your source code. That's not going to work. You need to put it in the folder that contains the generated executable. To find that folder, right-click on your app under Products and select Show In Finder.
This image shows what it looks like for a command line program. It also shows the Finder window that was opened. As you can see, it is a different folder than the one containing the source code.
As suggested by nepete, edit the scheme, but use $PROJECT_DIR as the custom working directory. Helps with moving the project around, or working in two different environments (e.g., home and office).
BTW. $PROJECT_DIR is one of the Xcode Environment Variables, and also helps with passing file names as command line arguments to programs (settable under "Arguments" in the scheme).
I've struggled with the same problem today. I wanted to add C code to my Swift project and my file pointer was always NULL.
Unfortunately, in XCode 9 for iOS app, I couldn't change the working directory. Changing Build phases didn't help me either. After 4+ hours of trial and error, that's what I've come up with finally and it works:
when copying files to XCode, I've chosen "Create groups", but I needed to choose "Create folder references":
I created a new objective-c file (.m) and copied all my C code there.
I left untouched .h files (XCode generated bridging header and my own .h file with public functions declaration). Now my project structure looked like this:
In my dict.m file in place of previous plain c fopen part:
FILE *dic = fopen("dictionary.txt", "r");
I added obj-C code:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"dictionary" ofType:#"txt"];
FILE *dic = fopen([filePath cStringUsingEncoding: NSUTF8StringEncoding], "r");
And it works now without any problem! It's just amazing!
ps I decided to write this answer in case it will help someone like me and will save them some time. If you know how to change working directory in XCode 9 for iOS, please, leave me a comment - now I am really curious why I can't find it.

Not able to write to a file

My programs have been running properly for over a year. Today I copied the files onto a different system and compiled every program.
When I compile and run from Dev-c++ it writes data onto a text file like its supposed to, but when I click on the executable it creates, it does not write data onto the file. Everything else like input/output seems to work.
What procedure have I missed?
Ok i've given the program Full permision but it still does not write.
I'm quite puzzled, atleast if it didn't run when i compile it in the C++ environment i can keep checking my code, but only the .exe does not work, any other suggestions ?
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream bss2;
bss2.open("expat.txt",ios::app);
bss2 << 2 ;
bss2.close();
}
This is the sample code i tested out.
How do i find the Current working directory ?
Ok i changed a line to
bss2.open("c:\\expat2.txt",ios::app);
and now it works properly in the exe file.
but there's over 50 files and i prefer i didn't have to spell out the new path to each one, what workaround is there to set the directory to the one previously used ?
update 4 :
#define _POSIX_SOURCE
#include <unistd.h>
#undef _POSIX_SOURCE
#include <stdio.h>
main() {
char cwd[256];
int y;
if (chdir("/tmp") != 0)
perror("chdir() error()");
else {
if (getcwd(cwd, sizeof(cwd)) == NULL)
perror("getcwd() error");
else
printf("current working directory is: %s\n", cwd);
}
scanf(y);
}
Ok i used the getcwd() and this is the message it gives me
chdir() error(): No such file or directory
How do i set the directory now.
Sounds like your working directory isn't being set correctly when you double-click on the file. If you can access a log, use getcwd() and log what it returns.
I don't have Raymond Chen's psychic debugging powers yet, but I do know of a tool that may help you: Process Monitor. Use it to see precisely which files your application is trying to write to, and why it fails.
Maybe your looking at the wrong location. The program will write the file to the current working directory, which may be different between when you double click on the executable and run from Dev-C++.
The best and easiest way is to give the full path of the output file rather than just the filename. That way, you can be sure where the file went, and not have to search for it everywhere. If you are using Windows, the output file might be somewhere in system32. But I could be wrong.
As others have said, the working directory is likely incorrect.
If you create a shortcut to the .exe, you can set the working directory in the shortcut properties. Right-click on the shortcut, select "Properties", and change the "Start in" property.
Of course a better answer is to put the full path of the file into the filename string when you open it.
It might be that Windows uses backslash, so try "\tmp" instead of "/tmp".
Also if all your files are in the same directory, then you can use find & replace and replace open(" with open("c:\\your_directory_here\