writing a file in c++ with Xcode and running with terminal - c++

I'm very new to programming and i bought myself a self help book but the book is designed for windows. I've mostly been able to translate so far but i'm stumped on writing/appending files and running them through terminal. I was wondering if someone could translate these lines for me. these lines are what I'm told to type in command prompt/terminal.
C:\MyPrograms> c++ write.cpp -o write.exe
C:\MyPrograms> write
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string poem = "\n\tI never saw a man who looked" ;
poem.append("\n\tWith such a wistful eye") ;
poem.append("\n\tUpon that little tent of blue") ;
poem.append("\n\tWhich prisoners call the sky") ;
ofstream writer("poem.txt") ;
if (! writer)
{
cout << "Error opening file for output" << endl ;
return -1 ; //signal an error then exit the program.
}
writer << poem << endl ; // write output
writer.close() ; // close filestream.
return 0 ;
}
This is the program i am trying to run named write.cpp please help thanks!

On OS X, the first line in Terminal would be:
g++ write.cpp -o write
The second line would be:
./write
The first line compiles your code and creates an executable called write. The second line runs the executable.

Related

Script for running c++ inside Notepad++ without extra white line

I have a C++ script as follows:
NPP_SAVE
cd $(CURRENT_DIRECTORY)
g++ -o "$(NAME_PART).exe" "$(FULL_CURRENT_PATH)"
"$(NAME_PART).exe"
I try to compile my first C++ programming, print Hello, World.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
However, I see a an extra white line
Question:
How to delete it?
It means as following:

How to use file strings as commands in c++

I am trying to make a program on Windows 10 using Visual Studio 2015 that would sim-link certain files to certain locations. I am trying to make a text file with the location of the files, and the sim-link destination to use.
This is an example of the file data that would be in the properties.txt file:
FileLocation: "Z:\Folder\file.txt"
FileMkdirLocation: "Z:\Folder2\file.txt"
I want to use something like system(mkdir "sim-link_file_location" "file_location") by changing the data that is in properties.txt. I want to be able to add more than 1 file, without recompiling the program and writing each command for each file, one by one.
The problem is that I don't know how to make the commands use the data in the file.
EDIT: I managed to find out a way, but I get errors when compiling the program. I use this code:
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
using namespace std;
//initialization of Properties File used
ifstream PropertiesFile ("PropertiesFile.txt");
int main()
{
//initialization of variables used
int input_option;
char FileLocation[256], Command[]="mklink ";
// string FileLocation, Command;
PropertiesFile >> FileLocation;
/* switch (input_option)
{
case "add all mods":
}
*/
cout << "FileLocation: " << FileLocation;
cout << endl;
strcat(Command, FileLocation);
Command[strlen(FileLocation)] = '\0';
cout << Command;
cout << endl;
//system(command);
system("pause");
return 0;
}
I know that i haven't used all variables yet.
It tells me that "strcat" is deprecated and to use "strcat_s" instead, and when i replace it with that, I get
"Debug Assertion Failed - Expression: (L"Buffer is too small" && 0)"
I had to make the "Command" char bigger than "FileLocation" because then strcat_s would not be able to copy the content. After that the program worked fine, and there were no other Assert Errors.
The command to create a soft link in linux is: ln -s <source> <destination>
You can use this in a system(""); call, BUT before you continue in your code, you will have to make sure that the kernel finished executing this command.
After that you can read the link as if it was the original file.

How can I enter continuously by another C++ program in C system / popen command?

I want to build a compile system in an online judge system.
Environment: Ubuntu 12.04 LTS, g++ version 4.9
My workflow is "Compile cpp" -> "Execute it" -> "Record message".
But I got some problems when "the cpp file exist 'scanf' or 'cin' commands".
Because this is a auto-compile & run program, there is an other input need to load. (Is a string from function call not enter in terminal by myself)
My problem
How can I run the executeCommand (below code in compiler.cpp), using the string input (below too) to enter for this program. If the executed program exist any scanf, cin or other commands.
compiler.cpp
This is system command version, can replace to popen command too.
#include <string>
#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char ** argv) {
// Compiler one cpp file.
string compileCommand = "(g++ --std=c++11 ./main.cpp -o ./main.out) 2> main.err";
system(compileCommand.c_str());
// Execute this program.
string executeCommand = "(time timeout -k1s 0.01s ./main.out) > result.txt 2> time.txt";
system(executeCommand.c_str());
// I want the above main.out will scanf from this string.
string input = "Hello world, this is first line.\nThis is second line.";
return 0;
}
main.cpp
#include <stdlib.h>
#include <stdio.h>
int main () {
char str[256];
scanf("%s", str);
printf("%s\n", str);
return 0;
}
You probably need popen(3) (and you flagged your question as such).
FILE*pcmd = popen("time ./main.out", "w");
if (!pcmd) { perror("popen"); exit(EXIT_FAILURE); };
fprintf(pcmd, "Hello world, this is first line.\n");
fprintf(pcmd, "This is the second line.\n");
fflush(pcmd);
int bad = pclose(pcmd);
if (bad) {fprintf(stderr, "pclose failed %d\n", bad); };
Be aware of code injection issues, in particular when passing a computed command to popen or system
You might need some event loop around poll(2). Then use fork, execve, pipe and other syscalls(2) explicitly, so read Advanced Linux Programming
All you need is a pipe, system( "echo YOUR_STRING | ./main.out " )

Writing On Text File C++

I am simply trying to get a program to write "Test" to a created file. However, when I run the code below there is no file in the working directory. I am running this code on a Mac and compiling using gcc from Terminal.
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example-1.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
if (myfile.fail())
cout << "Fail" << endl;
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
All the code I posted is valid and works. However, I was compiling via the command line on a Mac OSX using gcc. The command looks like this:
g++ -g nameofinputfile.cpp -o nameofoutput.out
This works fine, however when you open the .out file (compilation file) the example-1.txt file is created at the root of the Users file where Documents, Desktop, Downloads etc. exist. Simply you just have to state where it is to be created. Refer to this question to learn how to specify the directory in your code.
You must use of fprintf() for write text on text files.
For example :
fp1=fopen("report.txt","a+");
fprintf(fp1,"Port is open: %d\n\n",i);
fclose(fp1);

In Embedded Octave C++ how do I execute a script file? ("error: invalid call to script")

I am writing a c++ oct-file that I would like to use as a link between my c++ code and scripts that were written in Octave. I can build and execute with no problems, and as long as I am doing simple things, it seems to work. I can even call functions in a script file with feval()! I just can't seem to figure out how to execute an entire script file..
If I try this simple program, I get an error, but I'm not sure why
#include <octave/oct.h>
#include <octave/octave.h>
#include <octave/parse.h>
#include <octave/toplev.h> // for do_octave_atexit
#include <iostream>
#include <string>
using namespace std;
void runscript(const string &file) {
cout << "attempting to run: " << file << endl;
int parse_status = 0;
eval_string(file, false, parse_status);
cout << "parse_status: " << parse_status << endl;
eval_string(file, false, parse_status, 0); // I'm not sure what the difference here is or
// what the value 0 means, I can't find any documentation on
// what `hargout` is.. See Note {1} below
cout << "parse_status: " << parse_status << endl;
}
int main(int argc, char **argv) {
// Set-up
char *oct_argv[3] = {(char*)"embedded", (char*)"-q", (char*)"--interactive"};
octave_main(3, oct_argv, true);
// Attempt to run script
runscript("Script1");
runscript("Script1.m");
// `a` should be defined after running Script1.m..
octave_value_list a = get_top_level_value("a", false);
do_octave_atexit ();
return 0;
}
Script1.m is very simple and looks like this:
a = 1000;
a
When I run, I always get this output:
attempting to run: Script1
error: invalid call to script /Users/Daly/Documents/School/EECS/Labs/GitHub/deep/Octave/ Script1.m
parse_status: 0
parse_status: 0
attempting to run: Script1.m
parse_status: 0
parse_status: 0
error: get_top_level_value: undefined symbol 'a'
It only ever complains about the invalid call the first time, no matter how many times I try to eval_string or in what order.
Notes: {1} After searching for error: invalid call to script, I found this source code which at line 00155 raises this exact error if nargout isn't 0, so I thought they might be related?
But anyway, maybe this isn't the right way to be going about it. What is the correct way to execute an entire octave script from an octave-embedded c++ program? Thanks!
You should be using the function source_file() rather than eval_string(). Take a look into the parser.h file which unfortunately doesn't have a lot of comments. The names are quite self-explanatory so you shouldn't have a lot of problems.
Also, you're pretty much trying to reimplement Octave's source function. If you really want to implement it again, look into the oct-parse.cc file (generated during the build process with flex and bison).