-
Notifications
You must be signed in to change notification settings - Fork 772
Programming Tricks, Part 1
Who needs an editor? IDE? We can just use cat
You've seen cat
being used to read the contents of files but it can also be used to simple echo back the output from standard-input stream
>cat
HELLO
HELLO
Let's use cat to send standard input to a file. We will use '>' to redirect output to a file:
>cat > myprog.c
#include <stdio.h>
int main() {printf("Hi!");return 0;}
(Be careful! Deletes and undos are not allowed...)
To tell the cat process the file has finished we need to close the input stream by pressing CTRL
-D
A useful trick if you have several files to change is to use regular expressions. perl makes this very easy to edit files in place. Just remember 'perl pie' and search on the web...
An example. Suppose we want to change the sequence "Hi" to "Bye" in all .c files in the current directory...
perl -p -i -e 's/Hi/Bye/' *.c
(Don't panic, original files are still there; they just have the extension .bak) Obviously there's a lot more you can do with regular expressions than changing Hi to Bye.
Tired of running make
or gcc
and then running the program if it compiled OK? Instead, use && to chain these commands together
gcc program.c && ./a.out
Use the C pre-processor to redefine common keywords e.g.
#define if while
Protip: Put this line inside one of the standard includes e.g. /usr/include/stdio.h
OK, so this is more of a gotcha. Be careful when using macros that look like functions...
#define min(a,b) a<b?a:b
A perfectly reasonable definition of a minimum of a and b. However the pre-processor is just a simple text wrangler so precedence can bite you:
int value = -min(2,3); // Should be -2?
Is expanded to
int value = -2<3 ? 2 :3; // Ooops.. result will be 2
The fix
is to wrap every argument with ()and also the whole expression with ():
#define min(a,b) ( (a) < (b) ?(a):(b) )
However this is still not a function. For example can you see why min(i++,10)
might implement i once or twice!?
Legal and Licensing information: Unless otherwise specified, submitted content to the wiki must be original work (including text, java code, and media) and you provide this material under a Creative Commons License. If you are not the copyright holder, please give proper attribution and credit to existing content and ensure that you have license to include the materials.