Code Blocks redirecting input output - c

I'm new to code blocks, and I can't seem to get it to work with command line arguments of < input > output. Does anyone know how to?
I'm currently able to read a file passed from argv[1] but, the program doesnt automatically read the input from the given file nor does it right the output to the file output.
I'm aware it is on set program's arguments, my arguments line is: list.txt < input > output
After some research I saw a guy doing it like this: < ./input > ./output, seems like running a program to give the input and output, anyways, I've also tried that to no avail. Do I need to use file handlers to interact with it? It doesn't make sence, simple getchar() should read from the passing input file.
What am I missing here?
Thanks in advance

I have found a way how to do it in CB 13.12
Tools -> Configure Tools -> Add:
Name: whatever
Executable: C:\Windows\System32\cmd.exe
Parameters: /C ${TARGET_OUTPUT_BASENAME} exampleArg1 <inputFileRedirect.txt
Working Directory: ${TARGET_OUTPUT_DIR}
It basicaly launches windows console and passes Parameters to it.
You can also assign keyboard shortcuts to these tools.
The only disadvantage i can see is that the tools are not project specific.

I've been working with Code::Blocks for some time now and just recently noted the same at least with Code::Blocks 12.11 in Windows. The redirections > and < do not work in the Project -> Set programs arguments...
A hackish solution is to do the execution in post-build step.
Right click project name -> Build options... -> Pre/post build steps -> Post-build steps:
cmd /C cd /D "bin\$(TARGET_NAME)\" & YourApplicationNameHere.exe >output.txt 2>errors.txt
And check the checkbox Always execute, even if target is up-to-date.
Now hit Ctrl+F9 and the program is executed as a last step of the building process.

I think it is the problem of cb_console_runner.exe which launches your program in IDE. ConsoleRunner can not interpret redirection symbol. So, I add some code to the original code of codeblocks 13.12.
Please copy linked file to [cb folder]. (Don't forget back-up the original.)
binary :
http://limity.tistory.com/attachment/cfile30.uf#241A8D485621595131B28F.exe
source code :
http://limity.tistory.com/attachment/cfile23.uf#231AF3485621595232A632.cpp

I was able to get input redirected to my c program by setting program arguments in project menu.
Navigate to Top Menu>Project>Set programs' arguments and put </absolute/path/to/yourinputfile notice < in start it tricks codeblocks into redirecting file instead of passing argument.

I tried almost all of the options & failed to make it work :P
After becoming fed up with all that, I basically use file processing to get my work done ( phew )
here is what I did in the code
At global scope I wrote :
#define DEBUG
#ifdef DEBUG
#include<fstream>
ifstream Inputfile;
ofstream Outputfile;
#define cin Inputfile
#define cout Outputfile
#endif //#ifdef DEBUG
& in main I wrote the following before doing anything else:
int main(){
#ifdef DEBUG
Inputfile.open("Input.txt");
Outputfile.open("Output.txt");;
#endif // #ifdef DEBUG
Finally just before closing the main process did this :
#ifdef DEBUG
Inputfile.close();
Outputfile.close();
#endif // #ifdef DEBUG
After this added two files
Input.txt
&
output.txt
to the project
This worked as expected

I know this is an old topic, but none of the solutions are good enough. For Windows, I would probably go with the following macro definition (as you may need it also for debug printing or similar) at global scope
#include <cstdio>
#ifdef DEBUG
#define D(X) X
#else
#define D(X)
#endif
Then as the first or second line (if you need std::ios::sync_with_stdio(false); ) in main use it as
int main() {
D(freopen("input.txt","r",stdin);)
D(freopen("ouput.txt","w",stdout);)
...
And define in Code::Blocks under Projects > Build Options... > (Debug, Compiler Settings, #defines)
DEBUG
Expecting that "input.txt" is the text input file in the folder where rest of the .c or .cpp files are, and "output.txt" will be the output file generated in the same folder (or they can be both added to the project as such files for easier editing/viewing).
This solution will work with both cin/cout and scanf/printf.

Related

YouCompleteMe suggests only "local" used code

I'm trying to use YCM for the first time so in order to make it work I decided to give a chance for the YCM-Generator, which generates the .ycm_extra_conf.py file automatically based on the makefile.
So far my program is just a simple hello world.
#include <stdio.h>
int main()
{
printf("Hello World!");
return 0;
}
I'm using the CMakeLists.txt trick to generate the makefile.
file(GLOB sources *.h *.c)
add_executable(Foo ${sources})
then after executing the YCM-Generator script, I get this output
Running cmake in '/tmp/tmp_YknVy'... $ cmake
/home/pedro/Desktop/Projetos/teste
Running make... $ make -i -j4
Cleaning up...
Build completed in 1.5 sec
Collected 2 relevant entries for C compilation (0 discarded).
Collected 0 relevant entries for C++ compilation (0 discarded).
Created YCM config file with 0 C flags
YCM plugin does find the .ycm_extra_conf.py file, but the auto-completion doesn't work right, for example, if I type "floa", it doesn't suggests "float", but It only suggests things that I used before like "int" or "printf".
Am I missing something or this is working as intended?
So I fixed it.
For c it does require a .ycm_extra_conf.py , while a friend of mine could make it work without one in c++.
The auto complete only suggest automatically functions that were previously used, if you don't remember a function name you have to press <Ctrl-Space>
YCM-Generator didn't do the job, so I modified the example file myself following the comments.
If you are used to Visual Assist, the auto complete works but it's really weak if compared to VA, which is a shame... I really hope someone port that plugin to Linux.

How to execute a C file through cmd

In my current example, I have a C file called 'Main.c' which converts and prints US pounds into UK stones/UK pounds/kilos, and the variable US pounds is currently defined by the user's input (scanf). The file itself is executed through Visual Express 2013; however, I want to change this so that I can navigate to the C file and execute the file directly through the commmand prompt (cmd) whiles passing a value to define US pounds.
I understand that this is required in main:
void main(int argc, char *argv[])
And I know how to navigate to the C file through the command prompt:
>cd Directory/To/The/File
However this is where I get stuck; I don't know how to execute the C file. I have researched into this and found several examples, such as using 'gcc' and 'cc', but the system doesn't recognise these commands. None of the materials that I have found fully explains what exactly I have to do in order to accomplish what I am trying to do; do I have to install something, or am I using the wrong commands, is it possible what I am trying to do, what excactly do I have to do?
Broadly speaking, you need to do the following:
Compile the program using a compiler to generate an executable.
Run the executable file.
When you "run the program in Visual Studio", it is doing all of those steps for you.
I don't know much about command line compiling in Windows, but I believe msbuild is the name of the compiler which Visual Studio uses. Look into that, and you'll see how to compile. Compilation will then generate the executable, which you just type into the command line to run.
EDIT: I found an article which suggests that cl is a C compiler command available on the command line.
Here is the relevant excerpt:
At the command prompt, specify the cl command together with the name of your source file—for example, cl simple.c—and press Enter to compile the program. The cl.exe compiler generates an .obj file that contains the compiled code, and then runs the linker to build an executable program that has the name of your source file, but has an .exe file name extension—for example, Simple.exe.
You cannot cd to the file, only to the directory. The cd command means "change directory".
You cannot execute a C file, it's just a text file and your computer doesn't know how to run it. You need to compile it first (this is what Visual Studio does). There should be an EXE file somewhere close, you need to find it. It is the binary, executable, form of your C program which you can run directly from the command line.

How to use bin2h?

I'm trying to use bin2h to convert a font file (font.ttf) into a C file but it won't work.
Can someone please tell me the syntax to save the output to a text file?
I've been trying to figure this out but nothing is working, and it's driving me insane. I'm really frustrated because I know the tool is working (I got it to work like a year ago) but I can't remember how I used it.
The example syntax on that site doesn't really help...
Please
Thanks to Lightness Races in Orbit's comment below I finally got the syntax right!
bin2h -cz font < font.ttf > output.h
That's working, thanks
Perhaps you are looking at the usage example on the website and not realising that it is a program that you execute from shell? It is not a line of C code.
So if you want to use this from a C program, you will need to execute it through a function like system or exec. However, since its output is a line of C code, you'd be better off running it from within your build script to create a C script, that you'd then link in to the rest of your program.
Example (in C++ as my C is rusty — port to C as required):
Source code for main.cpp
#include <iostream>
#include "eula.h"
int main()
{
std::cout << std::string(eula, eula_size) << std::endl;
}
Build commands
$ bin2h -cz eula < eula.txt > eula.h
$ g++ main.cpp -o myProgram
Execution command
$ ./myProgram
I would just write my own.
Here's the algorithm:
Open the source code file as text output.
Open the font file as binary input.
Write the array declaration to the output file, something like:
static const unsigned char font[] =
{
While the font file is not empty do:
Read unsigned char from font file, using binary read methods.
Output the unsigned char, in text format, to the source file.
end-while
Write the ending brace and semicolon to the source file.

Linux C: Shell-like environment - for individual execution - of C commands? (C interpreter)

Sorry if the question is worded wrong - I don't know the right word for what I'm asking for! :)
Say, you have some simple C program like:
#include <stdio.h>
int main()
{
int a=2;
printf("Hello World %d\n", a);
return 0;
}
Typically, this would have to be saved in a file (say, hello.c); then we run gcc on the source file and obtain executable file - and if we compiled in debug information, then we can use gdb on the executable, to step through lines of code, and inspect variables.
What I would like to have, is basically some sort of a "C" shell - similar to the Python shell; in the sense that I can have a sequence of Python commands in a file (a script) - or I can just paste the same commands in the shell, and they will execute the same. In respect to the simple program above, this is what I'd like to be able to do (where C> represents the imagined prompt):
C> #include <stdio.h>
(stdio.h included)
C> int a=2;
C> printf("Hello World %d\n", a);
Hello World 2
C>
In other words, I'd like to be able to execute individual C commands interactively (I'm guessing this would represent on-the-fly compilation of sorts?). Initially I was misled by the name of the C shell (csh) - but I don't think it will be able to execute C commands on the fly.
So, first and foremost, I'd like to know if it is possible somehow to persuade, say, gdb to perform in this manner? If not, is there anything else that would allow me to do something similar (some special shell, maybe)?
As for the context - I have some code where I have problems troubleshooting pointers between structs and such; here the way gdb can printout structs works very well - however, to isolate the problem, I have to make new source files, paste in data, compile and debug all over again. In this case, I'd much rather have the possibility to paste several structs (and their initialization commands) in some sort of a shell - and then, inspect using printf (or even better, something akin to gdb's print) typed directly on the shell.
Just for the record - I'm not really persuaded something like this really exists; but I thought I'd ask anyways :)
Thanks in advance for any answers,
Cheers!
EDIT: I was a bit busy, so haven't had time to review all answers yet for accept (sorry :) ); just wanted to add a little comment re:"interpreted vs. machine code"; or as mentioned by #doron:
The problem with running C /C++ source interactively is that
the compiler is not able to perform line by line interpretation of the code.
I am fully aware of this - but let's imagine a command line application (could even be an interpreted one), that gives you a prompt with a command line interface. At start, let's assume this application generates this simple "text file" in memory:
##HEADER##
int main()
{
##MAIN##
return 0;
}
Then, the application simply waits for a text to be entered at the prompt, and ENTER to be pressed; and upon a new line:
The application checks:
if the line starts with #define or #include, then it is added below the ##HEADER## - but above the int main() line - in the temp file
anything else, goes below ##MAIN## line - but above return 0; line - in the temp file
the temp file is stripped of ##HEADER## and ##MAIN## lines, and saved to disk as temp.c
gcc is called to compile temp.c and generate temp.out executable
if fail, notify user, exit
gdb is called to run the temp.out executable, with a breakpoint set at the return 0; line
if fail, notify user, exit
execution is returned to the prompt; the next commands the user enters, are in fact passed to gdb (so the user can use commands like p variable to inspect) - until the user presses, say, Ctrl+1 to exit gdb
Ctrl+1 - gdb exits, control is returned to our application - which waits for the next code line all over again.. etc
(subsequent code line entries are kept in the temp file - placed below the last entry from the same category)
Obviously, I wouldn't expect to be able to paste the entire linux kernel code into an application like this, and expect it to work :) However, I would expect to be able to paste in a couple of structs, and to inspect the results of statements like, say:
char dat = (char) (*(int16_t*)(my->structure->pdata) >> 32 & 0xFF) ^ 0x88;
... so I'm sure in what is the proper syntax to use (which is usually what I mess up with) - without the overhead of rebuilding and debugging the entire software, just to figure out whether I should have moved a right parenthesis before or after the asterisk sign (in the cases when such an action doesn't raise a compilation error, of course).
Now, I'm not sure of the entire scope of problems that can arise from a simplistic application architecture as above. But, it's an example, that simply points that something like a "C shell" (for relatively simple sessions/programs) would be conceptually doable, by also using gcc and gdb - without any serious clashes with the, otherwise, strict distinction between 'machine code' and 'interpreted' languages.
There are C interpreters.
Look for Ch or CINT.
Edit: found a new (untested) thing that appears to be what the OP wants
c-repl
Or just use it [...] like driving a Ferarri on city streets.
Tiny C Compiler
[... many features, including]
C script supported : just add '#!/usr/local/bin/tcc -run' at the first line of your C source, and execute it directly from the command line.
When your CPU runs a computer program, it runs something called machine code. This is a series of binary instructions that are specific to the CPU that you are using. Since machine code is quite hard to hand code, people invented higher level languages like C and C++. Unfortunately the CPU only understands machine code. So what happens is that we run a compiler that converts the high-level source language into machine code. Computer languages in this class are compiled language like C and C++. These languages are said to run natively since the generated machine code is run by the CPU without any further interpretation.
Now certain languages like Python, Bash and Perl do not need to be compiled beforehand and are rather interpreted. This means that the source file is read line by line by the interpreter and the correct task for the line is performed. This gives you the ability run stuff in an interactive shell as we see in Python.
The problem with running C /C++ source interactively is that the compiler is not able to perform line by line interpretation of the code. It is designed solely to generate corresponding machine code and therefore cannot run your C / C++ source interactively.
#buddhabrot and #pmg - thank you for your answers!
For the benefit of n00bery, here is a summary of the answers (as I couldn't immediately grasp what is going on): what I needed (in OP) is handled by what is called a "C Interpreter" (not a 'C shell'), of which the following were suggested:
CINT | ROOT - Ubuntu: install as sudo apt-get install root-system-bin (5.18.00-2.3ubuntu4 + 115MB of additional disk space)
c-repl (c-repl README)- Ubuntu: install as sudo apt-get install c-repl (c-repl_0.0.20071223-1_i386.deb + 106kB of additional disk space)
Ch standard edition - standard edition is freeware for windows/Unix
For c-repl - there is a quick tutorial on c-repl homepage as an example session; but here is how the same commands behave on my Ubuntu Lucid system, with the repository version (edit: see Where can I find c-repl documentation? for a better example):
$ c-repl
> int x = 3
> ++x
> .p x
unknown command: p
> printf("%d %p\n", x, &x)
4 0xbbd014
> .t fprintf
repl is ok
> #include <unistd.h>
<stdin>:1:22: warning: extra tokens at end of #include directive
> getp
p getp
No symbol "getp" in current context.
> printf("%d\n", getpid())
10284
> [Ctrl+C]
/usr/bin/c-repl:185:in `readline': Interrupt
from /usr/bin/c-repl:185:in `input_loop'
from /usr/bin/c-repl:184:in `loop'
from /usr/bin/c-repl:184:in `input_loop'
from /usr/bin/c-repl:203
Apparently, it would be best to build c-repl from latest source.
For cint it was a bit difficult to find something relateed to it directly (the webpage refers to ROOT Tutorials instead), but then I found "Le Huy: Using CINT - C/C++ Interpreter - Basic Commands"; and here is an example session from my system:
(Note: if cint is not available on your distribution's package root-system-bin, try root instead.)
$ cint
cint : C/C++ interpreter (mailing list 'cint#root.cern.ch')
Copyright(c) : 1995~2005 Masaharu Goto (gotom#hanno.jp)
revision : 5.16.29, Jan 08, 2008 by M.Goto
No main() function found in given source file. Interactive interface started.
'?':help, '.q':quit, 'statement','{statements;}' or '.p [expr]' to evaluate
cint> L iostream
Error: Symbol Liostream is not defined in current scope (tmpfile):1:
*** Interpreter error recovered ***
cint> {#include <iostream>}
cint> files
Error: Symbol files is not defined in current scope (tmpfile):1:
*** Interpreter error recovered ***
cint> {int x=3;}
cint> {++x}
Syntax Error: ++x Maybe missing ';' (tmpfile):2:
*** Interpreter error recovered ***
cint> {++x;}
(int)4
cint> .p x
(int)4
cint> printf("%d %p\n", x, &x)
4 0x8d57720
(const int)12
cint> printf("%d\n", getpid())
Error: Function getpid() is not defined in current scope (tmpfile):1:
*** Interpreter error recovered ***
cint> {#include <unistd.h>}
cint> printf("%d\n", getpid())
10535
(const int)6
cint> .q
Bye... (try 'qqq' if still running)
In any case, that is exactly what I needed: ability to load headers, add variables, and inspect the memory they will take! Thanks again, everyone - Cheers!
Python and c belongs to different kinds of language. Python is interpreted line by line when running, but c should compile, link and generate code to run.

How do I stop a command prompt from appearing in a Win32 C application?

I really have no idea why this is happening...
I created a win32 application in emacs, and whenever I make it and run it (not through the command prompt), a command prompt window pops up under the window. If I build a win32 application in Code::Blocks, and just run its default template, then it runs without a command prompt window. I looked all through the code of both and can't figure out what might cause this...
I thought it was because I included some printf() statements in there, but I didn't want them to stay there (they were for debugging), so I wrote a macro:
#define DEBUG
in main.c, and
#ifdef DEBUG
#include<stdio.h>
#define DBG printf
#else
#define DBG
#endif
in a header (included after the #define DEBUG of course).
When I undef'd DEBUG, the window still showed up... I don't know what I am doing to make it happen, what sorts of things cause a command prompt window to show up in a win32 application? I tried using all the ****Ex() windows functions instead of just CreateWindow(), etc, but that didn't change anything. I checked and re-checked the class definition and registration, to no avail, and made sure I didn't forget a printf() statement (which would have caused an error even if I did, since stdio.h isn't included unless DEBUG is defined).
This is what I included:
#include<windows.h>
#include<windowsx.h>
#include"main.h"
#include"windowproc.h"
anyone know what can cause this? I even commented out all of my stdio, DBG, printf junk, and it still showed up, and I swear there's no difference between my code and the Code::Blocks generated code, aside from my use of HANDLE_MSG and a few extra functions to split up the code.
Update
I am using MinGW 3.4.5.
using the -mwindows switch worked, thanks
Try linking with the -mwindows switch.
Your program should also have the main method read like so:
int WINAPI WinMain(
....
)
as opposed to the traditional int main().
Related threads:
Why does my QT4.5 app open a console window under Windows?
GCC / C how to hide console window?
Windows makes a difference between "console" and "Windows" applications. Console applications will always be run with an associated terminal.
See this question for details on the differences.
Don't know what compiler you are using but I know GCC needs the -mwindows option to suppress the command line window.

Resources