I am trying to build a shell program with a c program. Basically I need a text file with the same shell commands repeated over and over but with one part changed. I tried to build a C program to count from 1 to 750 and print out the paragraph with that one digit changed but it is trying to read the shell commands and giving me errors. How do I have it ignore the shell commands and just print what's in the printf?
Here is the program:
#include <stdio.h>
int main ()
{
int x;
for(x=1;x<751;x++){
printf("#!/bin/sh");
printf("NRNHOME="/Applications/NEURON-7.3/nrn"");
printf("\NEURONHOME="${NRNHOME}/share/nrn"");
printf("CPU=i386");
printf("NRNBIN="${NRNHOME}/i386/bin/"");
printf("PATH="${NRNHOME}/i386/bin:${PATH}"");
printf("export NRNHOME");
printf("export NEURONHOME");
printf("export NRNBIN");
printf("export PATH");
printf("export CPU");
printf("nrncarbon=yes");
printf("export nrncarbon");
printf("cd "\${NRNHOME}/i386/bin"");
printf("./nrngui.sh "/Applications/NSD2013/s%d.hoc"\n\n",x);
}
}
It's telling me all the directories are undeclared and it expects a ) before $? All I want is to have it print out the commands changing the .hoc file in the very last line beginning with s1.hoc and ending with s750.hoc.
Thanks in advance for your advice.
Aside from the fact that your program will generate a relatively useless long output list of 750 times almost the same script that you will probably have to chop up in 750 separate scriptfiles, there are a number of concrete problems that cause it to malfunction:
printf("#!/bin/sh");
because this statement is inside the loop, it will be
printf doesn't add newlines by itself, add \n if you want the next printf to start on a new line
printf("\NEURONHOME="${NRNHOME}/share/nrn"");
Pretty sure that \N at the start is unintentional
double quotes inside the string should be escaped, eg \"
printf("cd "\${NRNHOME}/i386/bin"");
Not sure why you seem to escape the $ here...
printf("./nrngui.sh "/Applications/NSD2013/s%d.hoc"\n\n",x);
}
Anyways, it's pretty easy to do this in pure shellscript, and send the output to 750 different script files in 1 blow:
for i in {1..750} ; do
cat << EOT > the_output_script$i.sh
#!/bin/sh
NRNHOME="/Applications/NEURON-7.3/nrn"
...
# If you want bash to ignore variables that should be evaluated later on
# you just need to escape the dollarsign
NRNBIN="\${NRNHOME}/i386/bin/"
./nrngui.sh "/Applications/NSD2013/s$i.hoc
EOT
# we're after the end of the heredoc, so here we can add other stuff that
# needs to be done in the loop, like changing the file's access:
chown ug+x the_output_script$i.sh
done
which will produce 750 files named the_output_script1.sh to the_output_script750.sh which is what I think you're really looking for. Btw, the core trick used in this script is called a heredoc or here document
Ok, to maintain your original intent (for educational purposes only):
#include <stdio.h>
int main ()
{
int x;
for(x=1;x<751;x++) {
printf("#!/bin/sh\n");
printf("NRNHOME=\"/Applications/NEURON-7.3/nrn\"\n");
printf("NEURONHOME=\"${NRNHOME}/share/nrn\"\n");
printf("CPU=i386");
printf("NRNBIN=\"${NRNHOME}/i386/bin/\"\n");
printf("PATH=\"${NRNHOME}/i386/bin:${PATH}\"\n");
printf("export NRNHOME");
printf("export NEURONHOME");
printf("export NRNBIN");
printf("export PATH");
printf("export CPU");
printf("nrncarbon=yes");
printf("export nrncarbon");
printf("cd \"${NRNHOME}/i386/bin\"\n");
printf("./nrngui.sh \"/Applications/NSD2013/s%d.hoc\"\n\n",x);
}
}
Now, another way to do it would be (my_script.sh):
#!/bin/sh
NRNHOME=/Applications/NEURON-7.3/nrn
NEURONHOME=${NRNHOME}/share/nrn
CPU=i386
NRNBIN=${NRNHOME}/i386/bin/
PATH=${NRNHOME}/i386/bin:${PATH}
export NRNHOME
export NEURONHOME
export NRNBIN
export PATH
export CPU
nrncarbon=yes
export nrncarbon
cd ${NRNHOME}/i386/bin
./nrnqui.sh /Applications/NSD2013/s*.hoc // the lazy way
OR: my_script.sh: // with a for loop
#!/bin/sh
NRNHOME=/Applications/NEURON-7.3/nrn
NEURONHOME=${NRNHOME}/share/nrn
CPU=i386
NRNBIN=${NRNHOME}/i386/bin/
PATH=${NRNHOME}/i386/bin:${PATH}
export NRNHOME
export NEURONHOME
export NRNBIN
export PATH
export CPU
nrncarbon=yes
export nrncarbon
cd ${NRNHOME}/i386/bin
for i in {1..750}
do
./nrnqui.sh /Applications/NSD2013/s{$i}.hoc
done
This could do it,
#include <stdio.h>
int main ()
{
int x;
for(x=1;x<751;x++){
printf("#!/bin/sh\n");
printf("NRNHOME=\"/Applications/NEURON-7.3/nrn\"\n");
printf("NEURONHOME=\"${NRNHOME}/share/nrn\"\n");
printf("CPU=i386\n");
printf("NRNBIN=\"${NRNHOME}/i386/bin/\"\n");
printf("PATH=\"${NRNHOME}/i386/bin:${PATH}\"\n");
printf("export NRNHOME\n");
printf("export NEURONHOME\n");
printf("export NRNBIN\n");
printf("export PATH\n");
printf("export CPU\n");
printf("nrncarbon=yes\n");
printf("export nrncarbon\n");
printf("cd \"${NRNHOME}/i386/bin\"\n");
printf("./nrngui.sh \"/Applications/NSD2013/s%d.hoc\"\n\n",x);
}
}
I strongly recommend you to learn printf here. Refer sources given here to know about c language
Related
#include <Windows.h>
int main(){
printf("Enter name of program. \n");
char prog[300];
scanf("%s", prog);
HMODULE hModule = GetModuleHandleW((LPCWSTR)prog);
if (hModule){
IMAGE_DOS_HEADER* pIDH = (IMAGE_DOS_HEADER*)hModule;
IMAGE_NT_HEADERS* pNTH =(IMAGE_NT_HEADERS*)((BYTE*)pIDH + pIDH->e_lfanew);
IMAGE_OPTIONAL_HEADER pOPH = (IMAGE_OPTIONAL_HEADER)pNTH->OptionalHeader;
IMAGE_DATA_DIRECTORY* pIDD = (IMAGE_DATA_DIRECTORY*)pOPH.DataDirectory;
printf("%x", pIDD->VirtualAddress);
}
else {
printf("Error");
}
return 0;
}
That's my basic script for now only to check if I get into the IMAGE_DATA_DIRECTORY.
My goal is to print every dll and all of it's imported functions of a certain running process - GetModuleHandleA / W.
Every call its returning null - printing "Error" as I checked, excluding the empty call in which it prints '0' for some reason..
Besides the obvious (LPCWSTR)prog casting bug, GetModuleHandle is never going to work because it only handles modules in the current process.
Call CreateToolhelp32Snapshot to get a list of all processes and then call CreateToolhelp32Snapshot again to get the modules of a specific process. Note that you cannot read the DOS/NT headers of a remote process directly, you would have to use ReadProcessMemory.
DataDirectory is an array, you have to specify the directory you are interested in (resource, import, export etc.).
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have created a command line utility using C programming language. Now I want to embed that command into bash. It should act as bash built-in command 'cd'.
How can I do that??
In the bash source I saw there is a directory called builtins. I looked that directory and found there is *.def files and there is a file called cd.def.
I think this is the definition of bash built-in cd. Now my question is how to create my own definition???
If you wish to make your binary a built-in in bash
Method 1 : bash function
You can emulate the behavior by creating a bash function in, say ~/.bashrc, file:
function mycommand
{
/path/to/your/binary #plus arguments if any
}
export -f mycommand
and the use mycommand just like you use cd.
Do have a look at this [ tldp article ] on how this differ from an actual built-in.
Method 2 : using enable
I thought I would demonstrate this by creating a new builtin for finding factorial. Below is the code I've written :
/* Programme to compute the factorial of numbers up to 60 */
#include <bash/config.h>
#if defined(HAVE_UNISTD_H)
#include <unistd.h>
#endif
#include <bash/shell.h> // for shell internals
#include <bash/builtins.h> // for struct builtin
#include <stdio.h>
#include <stdlib.h> // for atoi
/* For unsigned long long numbers, my system could handle numbers
* upto 65 when it comes to factorial, but I'm restricting the value
* to 60 for the sake of the example so naming my builtin 'factorial60'
* the wrapper is factorial_wrapper and the actual task of computing the
* factorial is done by the function 'factorial'which resides inside the
* wrapper.
*/
unsigned long long factorial(unsigned long long x, unsigned long long amt)
{
if (x == 0)
return amt;
else
amt*=x;
return factorial(x-1, amt);
}
int factorial_wrapper(WORD_LIST* list) //Wrapper function
{
char* ptr=NULL;
int num;
if (list == 0) {
builtin_usage();
fflush(stdout);
return (EX_USAGE);
}
else{
ptr=list->word->word;
/* We're expecting one & only one argument here.
* I haven't checked for multiple arguments for the sake of brevity
*/
num=atoi(ptr);
/* atoi is not the best here because it returns zero for invalid conversions
* I used it just for the sake of this example.
*/
if (num>60){
builtin_usage();
fflush(stdout);
return (EX_USAGE);
}
printf("%llu\n",factorial(num,1));
fflush(stdout);
}
return (EXECUTION_SUCCESS); // returning 0
}
char *factorial60_doc[] = {
"factorial60",
"Usage : factorial60 number",
"Description :",
"Gives the factorial of numbers upto 60",
(char *)NULL
};
// Make sure the above documentation is sensible
// You need to supply factorial60_doc to the structure below.
struct builtin factorial60_struct = {
"factorial60", // builtin name
factorial_wrapper, // wrapper function for implementing the builtin
BUILTIN_ENABLED, // initial flags for builtin - See Reference 1
factorial60_doc, // array of long documentation strings.
"Usage : factorial60 'number_upto_60'", // usage synopsis; becomes short_doc
NULL // reserved for internal use, this a char*
};
Compile the code like below :
gcc -shared -fpic -o factorial.so factorial.c
Copy the shared object factorial.so to to a local lib location say /usr/local/lib/mylib/
Enable(persistent) the new builtin by adding the below in ~/.bashrc (or /etc/bash.bashrc if you wish the new builtin to be used by other users)
enable -f /usr/local/lib/mylib/factorial.so factorial60 # You need to give the full path
And voila! you have the new builtin ready for use in a new shell session.
$ factorial60 24
10611558092380307456
$ factorial60
factorial60: usage: Usage : factorial60 'number_upto_60'
$ type -a factorial60
factorial60 is a shell builtin
$ factorial60 61
factorial60: usage: Usage : factorial60 'number_upto_60'
(thanks #chepner for reminding this)
Method 3 : recompile bash
Just recompile bash(the dirty way!) with added functionality - [ source code here ].
References:
enable manpage [ here ].
WORD_LIST : Built-in functions are always given a pointer to a list of type WORD_LIST. If the built-in doesn't actually take any options, you must call no_options(list) and check its return value before any further processing. If the return value is non-zero, your function should immediately return with the value EX_USAGE. Check [ this ].
You need to install bash-builtins library (I'm on Ubuntu 12.04,The actual package name may differ by distro) to compile new builtins.
Check how builtin_usage is [ defined ].
To use the enable command, your system should support dynamic loading.
In enable the name of the builtin (here factorial60) should match the name given in the structure (notice factorial60_struct) and _struct should be appended to the builtin name in the structure.
You can also use alias, just adding the below line in ~/.bashrc will do the job.
alias commandname='/path/to/your/binary'
You could install it into a directly that part of your users path. Usually one of the following:
"/bin" or "/usr/bin" - you'll need root access on the machine to do this.
or
"~/bin" - if it just for your user and you don't have root access.
I have a huge code file and want to insert print code in every function.
I know debugging is one option but I am new to Kernel and kgdb is not an easy and immediate option hence I want to use printf temporarily.
I used vim's multiple buffers to do this task faster, but want to know if there is any way to automate it in .vimrc
Here is what the final code must look like
void foo(int a, int b) {
printf("Some print");
// ...
}
int bar() {
printf("Some print");
// ...
}
void bleh(int b) {
printf("Some print");
// ...
}
one quick way to do it is in the shell:
find -name '*.c' | xargs vim
In vim, you start recording with qq a macro, make use of the global command
:g/\v\s*(void|int) \w+\([^)]*\)/normal A^Mprint("some print");
And then you use the wonderful argdo command:
:argdo normal #q
To save the changes you use:
:argdo normal :w^M
That will add print("someprint") to every function on the located c source code files. If you want to use the function name or the file name in the print statement, you can use the global command with a little complex substitution like (not tested):
:global /\v\s*(void|int) \w+([^)]*)/s/\v(\w+)\([^]]*\)\s* {/\=submatch(0) . '\r\t\tprint(in file.function:'. expand('%') .'.'. submatch(1) . ');'
Remember that ^M and ^[ are not literal strings, they are inserted with <C-v><CR> and <C-v><Esc>
Hope this help
I am reading a file say x.c and I have to find for the string "shared". Once the string like that has been found, the following has to be done.
Example:
shared(x,n)
Output has to be
*var = &x;
*var1 = &n;
Pointers can be of any name. Output has to be written to a different file. How to do this?
I'm developing a source to source compiler for concurrent platforms using lex and yacc. This can be a routine written in C or if u can using lex and yacc. Can anyone please help?
Thanks.
If, as you state, the arguments can only be variables and not any kind of other expressions, then there are a couple of simple solutions.
One is to use regular expressions, and do a simple search/replace on the whole file using a pretty simple regular expression.
Another is to simply load the entire source file into memory, search using strstr for "shared(", and use e.g. strtok to get the arguments. Copy everything else verbatim to the destination.
Take advantage of the C preprocessor.
Put this at the top of the file
#define shared(x,n) { *var = &(x); *var1 = &(n); }
and run in through cpp. This will include external resources also and replace all macros, but you can simply remove all #something lines from the code, convert using injected preprocessor rules and then re-add them.
By the way, why not a simple macro set in a header file for the developer to include?
A doubt: where do var and var1 come from?
EDIT: corrected as shown by johnchen902
When it comes to preprocessor, I'll do this:
#define shared(x,n) (*var=&(x),*var1=&(n))
Why I think it's better than esseks's answer?
Suppose this situation:
if( someBool )
shared(x,n);
else { /* something else */ }
In esseks's answer it will becomes to:
if( someBool )
{ *var = &x; *var1 = &n; }; // compile error
else { /* something else */ }
And in my answer it will becomes to:
if( someBool )
(*var=&(x),*var1=&(n)); // good!
else { /* something else */ }
I have a function with an absurd number of return points, and I don't want to caveman each one, and I don't want to next through the function. Is there any way I can do something like finish, except have it stop on the return statement?
You can try reverse debugging to find out where function actually returns. Finish executing current frame, do reverse-step and then you should stop at just returned statement.
(gdb) fin
(gdb) reverse-step
There is already similar question
I think you're stuck setting breakpoints. I'd write a script to generate the list of breakpoint commands to run and paste them into gdb.
Sample script (in Python):
lines = open(filename, 'r').readlines()
break_lines = [line_num for line_num, line in enumerate(lines) if 'return' in line and
line_num > first and line_num <= last]
break_cmds = ['b %s:%d' % (filename, line_num) for line_num in break_lines]
print '\n'.join(break_cmds)
Set filename to the name of the file with the absurd function, first to the first line of the function (this is a quick script, not a C parser) and last to the number of the last line of the function. The output ought to be suitable for pasting into gdb.
Kind of a stretch, but the catch command can stop on many kinds of things (like forking, exiting, receiving a signal). You may be able to use catch catch (which breaks for exceptions) to do what you want in C++ if you wrap the function in try/finally. For that matter, if you break on a line inside the finally you can probably single-step through the return after that (although how much that will tell you about where it came from is highly dependent on optimization: common return cases are often folded by gcc).
How about taking this opportunity to break up what seems to be clearly a too-large function?
This question's come up before on SO. My answer from there:
Obviously you ought to refactor this function, but in C++ you can use this simple expedient to deal with this in five minutes:
class ReturnMarker
{
public:
ReturnMarker() {};
~ReturnMarker()
{
dummy += 1; //<-- put your breakpoint here
}
static int dummy;
}
int ReturnMarker::dummy = 0;
and then instance a single ReturnMarker at the top of your function. When it returns, that instance will go out of scope, and you'll hit the destructor.
void LongFunction()
{
ReturnMarker foo;
// ...
}