Running C scripts with terminal instead of Xcode - c

Currently I am developing a couple of C programs on my mac using Xcode. There however is 1 problem. My study requires me to use some sort of input field through the coding. So for instance if the users wants to run the program 10 times or wants the program to create 10 answers. I am using "atoi(argv[1])" just to get the input from the user.
This is exactly the problem. As soon as I run the program it just starts to bug, which is normal I quess because he is waiting for the input and not receiving it or something else. Anyways I tried to solve this problem with this link: How to run command-line application from the terminal?
This unfortunately didnt solve it either. I have already tried to re-install xcode, because just entering gcc in my terminal doesnt work either, but everytime the app store auto instals it for me.
Does anyone has a fix for my problem. I would greatly appreciate it due to the fact that next friday I have another deadline :( and I wont be getting a sufficient grade if my user input is not working.
Your help is again much appreciated!
Greetings,
Kipt Scriddy
EDIT: To clarify the problem. When running the script I want it to pop up in Terminal and wether there is an input field reguired it should ask for input. At the moment he is crashing immediatly due to the lack of input. He is not waiting for the argument to be passed from the users. He is skipping that part

HOWTO Pass command line arguments to your program from Xcode IDE
Open your project's active Scheme. Easiest way to do this is from the main menu. Select Product/Scheme/Edit Scheme...
In the schema editor, you'll see several build targets on the left side; the one you want is the "Run YourProjectName" target. Select it.
On the right side you'll see four sub-tabs, including Info, Arguments, Options, and Diagnostics. Select Arguments
Add/Remove any arguments you need. In your case, add /phi as the first argument, then 10 as the second.
Noteworthy: This is also where you can specify the current working directory of your program at launch rather than the long, temp path Xcode uses when building your binaries. To do so:
Perform steps 1-2 from above.
Select the Options sub-tab
Click the "Use custom working directory" checkbox.
Specify the full path where you want Xcode to execute your program from.
That in combination with getting your parameter handling fixed in your program should get you up and running.

Sounds to me like you want to get your arguments from the command line and if they are missing, prompt the user for them
Lets assume you want the arguments: number word number
#include <stdio.h>
#include <string.h>
int number1;
char word[128];
int number2;
int main(int argc, const char **argv)
{
if (argc == 4)
{
number1 = atoi(argv[1]);
strcpy(word, argv[2]);
number2 = atoi(argv[3]);
}
else
{
do
printf("Enter number word number: ");
while (scanf("%d %s %d", &number1, word, &number2) != 3);
}
printf("I got %d '%s' %d\n", number1, word, number2);
return 0;
}
Which gives:
$ ./test
Enter number word number: 1 andy 12
I got 1 'andy' 12
$ ./test 2 pandy 56
I got 2 'pandy' 56
Note that the error-checking is poor in this example and can be improved alot (not using atoi() is one way to start).

It sounds like you need to check argc in the program as RageD points out, otherwise when launching the program with insufficient arguments will cause problems.
gcc is the c compiler - it produces an executable. When you hit 'Run' in Xcode it compiles your program and then runs the executable file created. The executable created is named the same as your Xcode project name.
To run the program you built in Xcode from the command line:
In Xcode's project navigator find the executable in the 'Products' folder
Drag the executable file into Terminal (You will get an absolute url to the executable)
add any arguments you need to run your program
Hit enter!
The result will look something similar to the snippet below (for my 'MyCommandLineApp' project):
$ /Users/pliskin/Library/Developer/Xcode/DerivedData/MyCommandLineApp-hbpuxhguakaagvdlpdmqczucadim/Build/Products/Debug/MyCommandLineApp argument1 argument2

Related

Anyone know how to solve the error of "collect2.exe: error: ld returned 1 exit status" when a program in C is running?

First of all I'm at the first year of computer science so I'm a beginner in programming yet, then forgive me for my lack of knowledge. Well, my problem basically is an error that is shown in the screen everytime when I try to run(by the way I'm using Sublime Text) a program in C. In this case was a simple code:
#include <stdio.h>
int main() {
//print the heading of the game
printf("*****************************************\n");
printf("* Wellcome to the our guessing game *\n");
printf("*****************************************\n");
int secretnumber = 42;
int guess;
printf("What is your guess?");
scanf("%d", &guess);
printf("Your guess was %d \n", guess);
}
OUTPUT:
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: cannot open output file Olamundo.exe: Permission denied
collect2.exe: error: ld returned 1 exit status
[Finished in 0.3s]
You know, i tried some solutions like move the folder where the executable lies and place it in the root(in my case Mateus(C:)), give all the permissions to the folder, turn off the antivirus(in my case i just using the Windows defender), finish the task using the the Task manager but nothing worked. Please, help me i really don't know what else i can do.
Overall, your problem is that you're trying to run a program that is interactive from within Sublime; it doesn't support that. Sublime captures output your program sends to stdout and stderr and displays it in the output panel, but it does't connect the panel to stdin.
So, the scenario you're encountering works like this:
You run your program, which is interactive (in your case it prompts for input via scanf(), and it launches and prompts you for input
You try to enter input, but nothing happens because stdin isn't connected.
You try to run your program again (or modify it and build it again thinking you might have an issue).
The version you previously tried to run is still running in the background waiting for input you can't provide, and windows locks executable files while the program is running. So, when the linker (collect2) tries to link the executable during the build, it can't because the file is locked, hence the permission error.
You can clear the error by killing the program running in the background, which you can do via the Tools > Cancel Build if you do it before this error occurs; if you've already seen the error this likely won't work because this only cancels the most recent build, which would be the one where the error occurred.
The other thing you can do is use something external to kill it; the task manager on windows, kill from a terminal on Linux/OSX, etc. You'll need to do it this way if you're already seeing the error.
Note however that this doesn't solve your underlying problem because you're still trying to run an interactive program. In order to do that from within Sublime you need to create a custom sublime-build that allows for this. Generally you'd either have it spawn an external terminal and run the program in there, or use a package like Terminus if you want to keep it internal.
In order to set this up, you need to be familiar with the sequence of commands that are needed to compile, link and run a program in one command, which you can get by checking what the build system you're currently using is (assuming you didn't create it yourself).
This video on buffering and interactive builds in Sublime (disclaimer, I'm the author) has information and examples of how Terminus can be used for something like this if you'd like more information.

How can I see what I am writing in Netbeans when I run my code?

I use Netbeans for writing C.
My problem is: I cannot see the output of my code. I mean I can see the result but not the process itself.
For example:
#include <stdio.h>
int main(){
int n;
printf("please enter a number:\n");
scanf("%d",&n);
printf("your number's square is: %d", (n*n));
return 0;
}
When I run this code. Netbeans opens two windows.
one for "build, run" and one for "run". It allows me to write in the "run" window.
but I cannot see the text "please enter a number" or what I am writing. I only see a blank page but when I write a number then hit enter "twice". It shows all outputs in the same window at once. Like this:
please enter a number:
your number's square is: 25
RUN SUCCESSFUL (total time: 2s)
How can I see what I am writing?
I can reproduce your problem. This is a known issue with NetBeans 8.2, but I also see the same problem with NetBeans 11.2.
See these NetBeans Bug Reports:
Bug 165437 - Standard output in Output window is not flushed after '\n'
Bug 269406 - printf() doesnt output to console until scanf() end
Currently there is no fix for the issue, but there is a simple workaround:
Select your C project in the Projects panel.
Right click and select Properties from the context menu.
Select Run from the list of Categories.
Change Console Type from Internal Terminal to External Terminal.
Change External Terminal Type from Default to Command Window.
Click OK.
When you run your project the console will now open in a separate terminal window outside of NetBeans, and your code will work as expected:

Code wont compile or throw an error when using scanf in C, gets stuck building forever

I want to preface this with the information that I am pretty inexperience with coding.
Whenever I try to compile my code, it never finishes building and never throws an error. I then have to use Task Manager to stop stuck.exe (stuck is the name of the c file) so that I can try to compile again. I have narrowed down the issue to having something to do with the scanf function.
#include <stdio.h>
int main(void) {
int number = 0;
printf("this line shouldn't break anything. number = %d\n", number);
printf("what should the new value of number be?: ");
scanf("%d", &number);
return 0;
}
When I remove the line that has the scanf function, the rest of the code compiles as it should.
I am doing all of this in SublimeText3 on Windows 10 and using GCC provided by MinGW.
Any information you can give to help me would be appreciated, and If you would like any more information please let me know.
If you have a process stuck.exe, it means that the program finished compiling and was automatically started by the IDE/text editor. scanf reads from standard input, but apparently the IDE does not execute it in an interactive fashion, so that you cannot enter the number via the IDE.
In your IDE, you need to use the Compile or Build command (and not Run), and invoke stuck.exe manually in a command shell window.
Even my compiler is GCC-MinGW and i use Vscode, And your program works just fine even with online compilers.Maybe there is a problem with your C installation or check if your system memory near to full it might cause problems like these sometimes.

C/C++ BEGINNER - fgets with stdin causing unexpected 'loop' results

I'm a programming student who's only really looked at Java up until now. This semester is our first time using C and I'm having a lot of trouble wrapping my head around some of the simplest functions. I really have no idea what I'm doing. I couldn't even get Eclipse to work correctly with MinGW so I eventually gave up and reverted to Netbeans.
So basically I'm trying to use fgets to read user input for a switch-case menu, but I can't get fgets to work in even the simplest situations. To troubleshoot I tried copying a simple fgets example from online, but even that is giving me unexpected results.
When I run the code below it just runs an infinite empty loop (it does not prompt for user entry at all, it does not accept any user entry, it just 'runs' forever and the console remains blank). When I delete the fgets line and remove the other reference to the 'name' variable it works as you would expect (prints the user entry prompt and then ends).
Example code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
char name[10];
printf("Who are you? ");
fgets(name,10,stdin);
printf("Glad to meet you, %s.\n",name);
return(0);
return (EXIT_SUCCESS);
}
Any advice would be appreciated!
Other info:
I am running - Win 8 (poor me) & Netbeans IDE 8.0 (with MinGW)
When creating my C project I select File=> New Project=> C/C++=> C/C++ Application
EDIT: When I run the program I have tried:
1) right clicking the project file => Run; and
2) clicking the big green arrow in the netbeans ribbon;
.... neither works.
This code should work, but for you to be able to input anything, you need to run in in a proper terminal.
My guess is that you're running it inside your IDE and it's set to use pipes as stdin/stdout. Instead you should start cmd.exe and run the program in there (you'll have to navigate to the correct directory first).
Or, optionally, there might be a setting in your IDE to run the program using cmd.exe or with a builtin terminal.
A final note. You should learn to use sizeof whenever a buffer size is required. I.e. change this:
fgets(name,10,stdin);
to
fgets(name, sizeof(name), stdin);
Also, please use spaces to make your code more readable. Reading code is a big part of programming.
1) You might want to flush the file, after printf("Who are you? "); with fflush(stdout);
2) You have two return statements (which is harmless).
Other than that, your code is fine.
It works perfect - but you might want using fflush(stdin); before the fgets() call.
Also remember fgets return a string with '\n' after a user input - solved simply with name[strlen(name)-1]='\0'; - which is basically putting NULL as an "end of a string" symbol, basically you remove the '\n'.
And DO NOT change 10 to sizeof(name) - it doesn't matter at all, basically it's even supposedly worse as you can't use this in functions properly (sizeof(name) won't always match the length and would be the size of the pointer).
You should try compiling with MinGW if it didn't work, it will surely work on it.
A reminder: fgets() may let you enter MILLION characters, but it will take the first 10, in this case, at least.

Simple C Wrapper Around OpenSSH (with Cygwin on Windows)

I am packaging a program on Windows that expects to be able to externally call OpenSSH. So, I need to package ssh.exe with it and I need to force ssh.exe to always be called with a custom command line parameter (specifically -F to specify a config file it should use). There is no way to force the calling program to do this, and there are no simple ways to do this otherwise in Windows (that I can think of anyway - symlinks or cmd scripts won't work) so I was just going to write a simple wrapper in C to do it.
This is the code I put together:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int ret;
char **newv = malloc((argc + 2) * sizeof(*newv));
memmove(newv, argv, sizeof(*newv) * argc);
newv[argc] = "-F ssh.conf";
newv[argc+1] = 0;
ret = execv("ssh.orig.exe", newv);
printf("execv failed with return value of %i", ret);
return ret;
}
I then compile this code using GCC 4.6.3 in Cygwin and it runs without error; however, there is a strange behavior with regards to input and output. When you go to type at the console (confirming the authenticity of the host and entering in a password, etc) only part of the input appears on the console. For example, if I type in the word 'yes' and press enter, only the 'e' will appear on the console and SSH will display an error about needing to type 'yes' or 'no'. Doing this from the Windows command prompt will result in your input going back to the command propmt, so when you type 'yes' and press enter, you get the ''yes' is not recognized as an internal or external command...' message as if the input were being typed at the command prompt. Eventually SSH will time out after that.
So, I'm obviously missing something here, and I'm assuming it has something to do with the way execv works (at least the POSIX Cygwin version of it).
Is there something I'm missing here or are there any alternatives? I was wondering if maybe I need to fork it and redirect the I/O to the fork (although fork() doesn't seem to work - but there are other issues there on Windows). I tried using _execv from process.h but I was having issues getting the code right for that (also could have been related to trying to use gcc).
It's also possible that there may be a non-programming way to do this that I haven't thought of, but all of the possibilities I've tried don't seem to work.
Thoughts?
I ended up finding a solution to this problem. I'm sure there were other ways to do this, but this seems to fix the issue and works well. I've replaced the execv line with the following code:
ret = spawnv(P_WAIT, "ssh.orig.exe", newv);
You have to use 'P_WAIT' otherwise the parent process completes and exits and you still have the same problem as before. This causes the parent process to wait, but still transfers input and output to the child process.

Resources