question
stringlengths
25
894
answer
stringlengths
4
863
In pseudocode... ``` processHandle = _spawnl(_P_NOWAIT, "foo.exe", ...); /* time passes... */ WossnameKillFunction(processHandle); ```
There is no terminate counterpart to the VC++ function_spawnl(), but it does return a Win32HANDLEthat you can use: ``` HANDLE handle = (HANDLE)_spawnl(...); TerminateProcess(handle, exit_code); ``` Note it only returns aHANDLEif you call it with one of theNOWAITargs. If not, it will return the process's exit code. ...
printf statements with colour codes appear very brightly on Linux. ``` #define DBG_YELLOW "\033[33m" fprintf(stderr, DBG_YELLOW"%s %s\n"DBG_NORMAL, area, msg); ``` However those same printf's with colour codes appear quite dull on cygwin. any ideas what I can do to brighten them?
The colors for MinTTY can be changed, it seems. On Cygwin, you have the Windows terminal, MinTTY and rxvt as terminals. I'd say MinTTY is by far the best of those. Haha, good news: MinTTY now allows you tochange the 16 default ANSI colors, see the section "Changing colours"! And also seethis other question to pimp y...
I want to convert the following lines written in matlab to c++ ``` int i = 5; m=cos(pi*theta(i)/180.0); n=sin(pi*theta(i)/180.0); ``` Please Help! I am a newbie...
Though I'm not sure what the theta() function does in MATLAB, I'll make an attempt to answer your question: The C++ library you are looking for ismath.hIt has the sin() and cos() functions in it. List of all functions in math.h referthis page. Both sin() and cos() function accept one argument of type 'double', which...
What's the standard way to print to the right side and/or bottom side of the terminal window using n/curses? Here's a little sketch: ``` Terminal window: ================================================================================ [ MSG ] ...
I'd go with: ``` mvprintw(COLS-length("msg"),1,"msg"); mvprintw(0,LINES-1,"message number 2"); mvprintw(COLS-length("here is more"),LINES-1,"here is more"); ``` That's kinda off the cuff, which is how I do most of my curses programming.
How can i know the number of non Coalesced read/write and bank conflicts using parallel nsight?Moreover what should i look at when i use nsight is a profiler? what are the important fields that may cause my program to slow down?
I don't use NSight, but typical fields that you'll look at with a profiler are basically: memory consumptiontime spent in functions More specifically, with CUDA, you'll be careful to your GPU's occupancy.Other interesting values are the way the compiler has set your local variables: in registers or in local memory. ...
``` #include<stdio.h> main { int x[]={1,2,3,4,5}; int i,*j; j=x; for(i=0;i<=4;i++) { printf("%u",j); j++; } } ``` output: ``` 65512 65514 65516 65518 65520 ``` But when I change theprintfto" ``` printf("%u",&j[i]); ``` Output is: ``` 65512 65516 65520 65524 65528 ``` Why ...
You get jumps of 4 in the second example because you are incrementingjandoffsetting byi! Both of these contribute a difference of 2. Note also thatprintfis not type-safe; it is up to you to ensure that the arguments match the format-specifiers. You have specified%u, but you've given it anint *, you should use%pfor ...
What I know: When a process is running I can pressCtrl+Zand suspend it. The withbgandfgcommands I can either run it in "background" or "foreground" mode. What I'm aksing: Is there a way to suspend a process, send it to run in background or foreground in C? Edit:I have the process id. I want to send that process to...
You can suspend it withkill(pid, SIGSTOP), but making it foreground or background is a function of the shell that ran it, since what it actually affects is whether the shell displays a prompt (and accepts a new command) immediately or waits until the job exits. Unless the shell provides an RPC interface (like DBus), ...
This question already has answers here:float to int unexpected behaviour(6 answers)Closed6 years ago. ``` #include <stdio.h> int main() { float a = 12.5; printf("%d\n", a); printf("%d\n", *(int *)&a); return 0; } ``` Additionally, how do you interpret the expression*(int *)&a?
It takes the address of a float, casts it to an integer pointer and then dereferences that as an integer. Totally wrong. There are at least two things wrong here: Nobody says the pointers for an int and a float need to be the same sizeThe representation for a float looks nothing like the representation for a signed ...
I'm trying to understand what functionsmemalign()andposix_memalign()do. Reading the available documentation didn't help. Can someone help me understand how it works and what is it used for? Or, perhaps provide a usage example? I'm trying to understand how linux memory works, I need to write my own simple memory pool...
Whereasmallocgives you a chunk of memory that could have any alignment (the only requirement is that it must be aligned for the largest primitive type that the implementation supports),posix_memaligngives you a chunk of memory that is guaranteed to have the requested alignment. So the result of e.g.posix_memalign(&p,...
This question already has answers here:Closed12 years ago. Possible Duplicates:Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?What's the use of do while(0) when we define a macro? Is there a difference between ``` #define MACRO(x) \ { \ ... \ }...
do { ... } while(0) allows the macro to be used in conditional code. Looks like this question has been asked before:C multi-line macro: do/while(0) vs scope block Here's another linkto a couple of reasons to do so, and why to omit the semicolon at the end.
This question is in reference toHow can I get a file's size in C? Most answers suggesting the use of the function stat to get the file length also comes with a tag to do error checking. What kind of error checking do we need here? Thanks.
Like many Unix/POSIX API functions,stat(2)returns a negative integer on failure. Unfortunately, this integer is always -1 for stat. Hence, you need to check theerrnoglobal variable(defined in<errno.h>) to see what the exact error was. Ben has listedsome of the errors you can run into; the errno codes for these and ot...
Assume that there are flag definitions such as: ``` SHF_WRITE 0x1 SHF_ALLOC 0x2 SHF_EXECINSTR 0x4 SHF_MASKPROC 0xf0000000 ``` Given a flag, I need to outputSHF_WRITE|SHF_ALLOCif the bits0x1and0x2is on. How to do the trick in C?
``` #define V(n) { n, #n } struct Code { int value; char *name; } decode[] = { V(SHF_WRITE), V(SHF_ALLOC), { 0, NULL }, }; void f(const int x) { struct Code *c = decode; int beenthere = 0; for(; c->name; ++c) if(x & c->value) printf("%s%s", beenthere++ ? "|" : "", c->name); if(beenthere...
``` int main(int argc,char* argv[]); ``` If there's a'\0'character inA, will it be split into2arguments ? ``` ./programe "A" ``` I can't reproduce it easily as I can't put an'\0'intoA,but there might be someone who can.
Parameters are passed into programs as C strings; in particular, theexecve()syscall (lowest level visible to programs and generally ether very close to or identical to the kernel API) uses C strings, so it is not possible to pass\0within a parameter. Note that, while the usual way the parameter vector is passed into ...
I am using many of the array methods found in array.c of the ruby codebase, but when trying to call ``` VALUE rIntersection = rb_ary_and(rAry1, rAry2); ``` I got this error: ``` dyld: lazy symbol binding failed: Symbol not found: _rb_ary_and Referenced from: ./ext/ev/counters.bundle Expected in: flat namespace ...
Have a look athttp://www.ruby-doc.org/doxygen/1.8.4/array_8c-source.html(Line 2666) There you can see that the method rb_ary_and is declaredstatic. This means that it is only visible inside ofarray.c.
How to call Java methods from C program? I.e. is it possible to embed java (not necessary Sun/Oracle JVM) in other language?
A full Oracle JVM is a very large chunk to pull into your existing program, but it is perfectly doable but I would recommend against it if any of the following apply: You need to pull a lot of data in and out of the JVM on a frequent basis. This is expensive.You are not in full control of the operating system and JV...
I'm trying thegetoptAPI: http://www.gnu.org/s/hello/manual/libc/Example-of-Getopt.html#Example-of-Getopt But I find it only supports options in the middle? As I find that it's judgingargv[optind]toargv[argc-1]as non-opt arguments. Is that the case?
GNU getopt allows options anywhere on the command line. It re-ordersargvwhen parsing, though. You can verify this by saving the example code in a file, compiling it, and running the result: ``` ./a.out ./a.out -a ./a.out foo ./a.out -a foo ./a.out foo -a ``` The last two will give the same results.
I have the following file testf.h: ``` #ifndef TESTF_H_ #define TESTF_H_ int test(int what){ return what; } #endif ``` I included/imported it in TestAppDelegate.h (which is used for other .m files in my xcode project). I get a duplicate symbol error. If I included/imported testf.h in a .m file that is never incl...
This is a function definition, it belongs in a c, cpp or m file. This popular trick with #defines will protect you from compiler errors (typically to survive circular #include dependencies. ) It will not protect against a linker error. This is exactly why people put declarations in h files and definitions in c (or m)...
I am calling a command via system(command) call. But no other code is executed after this system() call. Why is so? I thought, system() would create a child process for "command" execution and my program (parent of "command"-child) will continue executing code after that. Am I not understanding system() correctly? ...
Thesystem(3)function causes your process to wait for the completion of the child. Edit 0: You have to use the classic pair offork(2)andexecve(2)for what you want to do. You might also check whether your C library provides POSIXspawn(3). Edit 1: Look intowaitpid(2)to keep the parent around.
hello i have to download a simple .txt file from web in c language. i have found a way with curl (tut) but now i want to know other ways. my application should check the content of file and return it. filecontent: ``` open ``` or ``` closed ``` Does someone knows any tutorials or codesnippets?
You need a tutorial about sockets and have to look up the HTTP spec. It's pretty simple.
I'm executing aDELETEstatement using the SQLite 3 C API, and I'd like to know how to fetch the number of affected rows. Unfortunately, there is no function such assqlite3_affected_rowsor similar.
Trysqlite3_changes()and/orsqlite3_total_changes()
I added .h/.cpp files with C functions to my Xcode project. How would I call a C function in an objective-C function? When I included the C file (#import "example.h") in the app delegate header file it exploded with errors (could be that it treated the cpp file as objective-c) even though it compiles fine without bei...
If you want to use C++ with your Objective-C module, change the file extension from.mto.mm.
I have this function that takes a pointer of an array (in order to modify it from within the function) ``` int func_test(char *arr[]){ return 0; } int main(){ char var[3]; func_test(&var); return 0; } ``` When I try to compile this I get : ``` passing argument 1 of ‘func_test’ from incompatible pointer ...
char * arr[]is not a pointer to an array; it is an array of pointers. Declarations in C are read first from the identifier towards the right, then from the identifier towards the left. So: ``` char * arr[]; // ^ arr is... // ^ an array of... // ^ pointers to... // ^ char ```
The application runs in Linux, Windows, Macintosh. Also, if yes, how much effort is required?
Does nginx run on windows? I think you'd have a much better result using an existing library that includes a good http server. My first choice would belibevent.
I found the example and metaphor ofObject#===operatorare too confusing, I'm now begin to read the source code, But I'm new to C, anyone could tell me how to analysis this code: ``` VALUE rb_equal(VALUE obj1, VALUE obj2) { VALUE result; if (obj1 == obj2) return Qtrue; result = rb_funcall(obj1, id_eq, 1, o...
VALUEis the generic type of Ruby objects in C (as opposed to the C types likeint). From this you can deduce thatrb_equalis a function comparing two Ruby objects (obj1andobj2). If the two objects are equalQtrue(the represantion of Ruby's true in C) will get returned. If notrb_funcallwill call the equality method (id_eq...
I have a C code that collects data and places them in a 2-D array. I would like to plot this data on an x-y graph (mathematics) automatically i.e. pass the data as parameters in a command line and get a graph Are there any suggestions for how to do so?
gnuplot is a good one to look at assume you mean x-y charts, if you want actual graphs then look at dot
I'm writing a VisualC++ program which have code invoke ffmpeg.exe to convert video file. I wonder is it possible to pause/resume ffmpeg converting thread from C++ code? LR.
All you need to do is suspend and resume the ffmpeg child process itself. The main problem is: there is no SuspendProcess API function. And there is no documented or safe way of doing this. The only simple way of doing this is via SuspendThread/ResumeThread. Seethis articleon codeproject about how to do it.
``` int main( ){ char a[2]; char *p; p=&a[0]; *(p+5)='g'; } ``` In the above program I defined a pointer pointing to char array but the array is 3 bytes only. Let me tell you more clearly,for instance let us assume the char array address is 1000 so it takes upto 1003 bytes, but using a pointer I a...
You are changing a random memory location in your program. This isundefined behaviorand it could have random effects on your program such as a segmentation fault.
I am using many of the array methods found in array.c of the ruby codebase, but when trying to call ``` VALUE rIntersection = rb_ary_and(rAry1, rAry2); ``` I got this error: ``` dyld: lazy symbol binding failed: Symbol not found: _rb_ary_and Referenced from: ./ext/ev/counters.bundle Expected in: flat namespace ...
Have a look athttp://www.ruby-doc.org/doxygen/1.8.4/array_8c-source.html(Line 2666) There you can see that the method rb_ary_and is declaredstatic. This means that it is only visible inside ofarray.c.
How to call Java methods from C program? I.e. is it possible to embed java (not necessary Sun/Oracle JVM) in other language?
A full Oracle JVM is a very large chunk to pull into your existing program, but it is perfectly doable but I would recommend against it if any of the following apply: You need to pull a lot of data in and out of the JVM on a frequent basis. This is expensive.You are not in full control of the operating system and JV...
I'm trying thegetoptAPI: http://www.gnu.org/s/hello/manual/libc/Example-of-Getopt.html#Example-of-Getopt But I find it only supports options in the middle? As I find that it's judgingargv[optind]toargv[argc-1]as non-opt arguments. Is that the case?
GNU getopt allows options anywhere on the command line. It re-ordersargvwhen parsing, though. You can verify this by saving the example code in a file, compiling it, and running the result: ``` ./a.out ./a.out -a ./a.out foo ./a.out -a foo ./a.out foo -a ``` The last two will give the same results.
I have the following file testf.h: ``` #ifndef TESTF_H_ #define TESTF_H_ int test(int what){ return what; } #endif ``` I included/imported it in TestAppDelegate.h (which is used for other .m files in my xcode project). I get a duplicate symbol error. If I included/imported testf.h in a .m file that is never incl...
This is a function definition, it belongs in a c, cpp or m file. This popular trick with #defines will protect you from compiler errors (typically to survive circular #include dependencies. ) It will not protect against a linker error. This is exactly why people put declarations in h files and definitions in c (or m)...
I am calling a command via system(command) call. But no other code is executed after this system() call. Why is so? I thought, system() would create a child process for "command" execution and my program (parent of "command"-child) will continue executing code after that. Am I not understanding system() correctly? ...
Thesystem(3)function causes your process to wait for the completion of the child. Edit 0: You have to use the classic pair offork(2)andexecve(2)for what you want to do. You might also check whether your C library provides POSIXspawn(3). Edit 1: Look intowaitpid(2)to keep the parent around.
hello i have to download a simple .txt file from web in c language. i have found a way with curl (tut) but now i want to know other ways. my application should check the content of file and return it. filecontent: ``` open ``` or ``` closed ``` Does someone knows any tutorials or codesnippets?
You need a tutorial about sockets and have to look up the HTTP spec. It's pretty simple.
I'm executing aDELETEstatement using the SQLite 3 C API, and I'd like to know how to fetch the number of affected rows. Unfortunately, there is no function such assqlite3_affected_rowsor similar.
Trysqlite3_changes()and/orsqlite3_total_changes()
I added .h/.cpp files with C functions to my Xcode project. How would I call a C function in an objective-C function? When I included the C file (#import "example.h") in the app delegate header file it exploded with errors (could be that it treated the cpp file as objective-c) even though it compiles fine without bei...
If you want to use C++ with your Objective-C module, change the file extension from.mto.mm.
I have this function that takes a pointer of an array (in order to modify it from within the function) ``` int func_test(char *arr[]){ return 0; } int main(){ char var[3]; func_test(&var); return 0; } ``` When I try to compile this I get : ``` passing argument 1 of ‘func_test’ from incompatible pointer ...
char * arr[]is not a pointer to an array; it is an array of pointers. Declarations in C are read first from the identifier towards the right, then from the identifier towards the left. So: ``` char * arr[]; // ^ arr is... // ^ an array of... // ^ pointers to... // ^ char ```
I have an unmanaged program (Fortran) that I'm adding a Version.rc resource file to include version information. Is there a way to update the last number of the version information at build time with a random number generated at each build? For example. ``` FILEVERSION = <major>,<minor>,<rev>,<build_hash> ``` wher...
As @Hans suggested above. The best approach was to add a pre-build event in Visual Studio that runs a script (Perl in this case) to reach into the *.rc file and change the to a random number.
If you had to convert ``` unsigned short data1[32] ``` to ``` unsigned char* data2 ``` in a tight loop to be executed 10 million times what function would you use to get the best performance?I am using this ``` reinterpret_cast<unsigned char*>(data1); ``` but was wondering if there is a better way
reinterpret_castis the holy grail of performance seeking coders, namely code that results in zero clock cycles.
I am porting c code of a firmware to c# and not sure how this keyword ``` "sbit" ``` can be written in c#. Thanks in advance.
link@Ben Robinson, "(...)With typical 8051 applications, it is often necessary to access individual bits within an SFR. The sbit type provides access to bit-addressable SFRs and other bit-addressable objects. For example: ``` sbit EA = 0xAF; ``` This declaration defines EA as the SFR bit at address 0xAF. On the 805...
I am using system() call to start "tail -f". One thing I saw was that, invocation of tail takes 2 processes (I can see in ps): 1) sh -c tail filename 2) tail filename As man page says: system() executes a command specified in command by calling /bin/sh -c command. I guess, process 1) is inevitable, correct? I was j...
It's better to usefork()/exec()to launch processes.system()invokes the shell, so you should take care with what you pass to it. ``` /* Untested code, but you get the idea */ switch ((pid = fork())) { case -1: perror("fork"); break; case 0: execl("/usr/bin/tail", "tail", "-f", filename); perror("execl"...
If we have a union with three variables int i, char c, float f; and we store a value in say the variable c now. and we forget what is the variable of the union that holds a value currently, after some time. for this is there any mechanism provided by the language using which we can find out whether it is i or c or f t...
It is not possible. The different members of a union all refer to the same memory adress, they are just differentways of seeingthat memory. Modifiying a member of the union modifies all the other. You cannot distinguish one from another.
I know I can get file size ofFILE *byfseek, but what I have is just a INT fd. How can I get file size in this case?
You can uselseekwithSEEK_ENDas the origin, as it returns the new offset in the file, eg. ``` off_t fsize; fsize = lseek(fd, 0, SEEK_END); ```
Can I authenticate a local Unix users using C? If so does anyone have a code snippet?
Good old way to do that, using /etc/shadow: ``` int sys_auth_user (const char*username, const char*password) { struct passwd*pw; struct spwd*sp; char*encrypted, *correct; pw = getpwnam (username); endpwent(); if (!pw) return 1; //user doesn't really exist sp = getspnam (pw->pw_name); endspent(); ...
Linux/C/pipes: How can I capture the output of ping command using popen(Or similar system calls). Currently popen will wait until ping is finished. Then output will be dumped together. Pseudo code: ``` fp= popen("ping x.x.x.x", "r"); while(!feof(pFp)) { if(fgets(fp ...) // <==currently the code blocks here until...
It's not waiting until ping is finished. Rather, ping is waiting until thestdoutbuffer fills up before writing anything. The only ways to avoid this involve pseudo-ttys. Either you should abandonpopenand write the code to run the ping child process yourself and use a pseudo-tty to communicate (this is easy with the no...
This question already has answers here:Closed12 years ago. Possible Duplicates:main(int argc, char *argv[])Main's Signature in C++ If i write: ``` int main(int argc, char** argv) ``` i get proper commandline input. What would happen if i wrote say, ``` int main(int foo, double fooDouble, fooType FooVar) ``` Is t...
Given that it does compile, it will still only be called with the argc and argv arguments. So your fooDouble will get the pointer value of argv, and FooVar will get whatever value is in that register/stack space used for that argument position (which may not have been initialized by the callee, so it may hold any und...
If we have a union with three variables int i, char c, float f; and we store a value in say the variable c now. and we forget what is the variable of the union that holds a value currently, after some time. for this is there any mechanism provided by the language using which we can find out whether it is i or c or f t...
It is not possible. The different members of a union all refer to the same memory adress, they are just differentways of seeingthat memory. Modifiying a member of the union modifies all the other. You cannot distinguish one from another.
I know I can get file size ofFILE *byfseek, but what I have is just a INT fd. How can I get file size in this case?
You can uselseekwithSEEK_ENDas the origin, as it returns the new offset in the file, eg. ``` off_t fsize; fsize = lseek(fd, 0, SEEK_END); ```
Can I authenticate a local Unix users using C? If so does anyone have a code snippet?
Good old way to do that, using /etc/shadow: ``` int sys_auth_user (const char*username, const char*password) { struct passwd*pw; struct spwd*sp; char*encrypted, *correct; pw = getpwnam (username); endpwent(); if (!pw) return 1; //user doesn't really exist sp = getspnam (pw->pw_name); endspent(); ...
Linux/C/pipes: How can I capture the output of ping command using popen(Or similar system calls). Currently popen will wait until ping is finished. Then output will be dumped together. Pseudo code: ``` fp= popen("ping x.x.x.x", "r"); while(!feof(pFp)) { if(fgets(fp ...) // <==currently the code blocks here until...
It's not waiting until ping is finished. Rather, ping is waiting until thestdoutbuffer fills up before writing anything. The only ways to avoid this involve pseudo-ttys. Either you should abandonpopenand write the code to run the ping child process yourself and use a pseudo-tty to communicate (this is easy with the no...
This question already has answers here:Closed12 years ago. Possible Duplicates:main(int argc, char *argv[])Main's Signature in C++ If i write: ``` int main(int argc, char** argv) ``` i get proper commandline input. What would happen if i wrote say, ``` int main(int foo, double fooDouble, fooType FooVar) ``` Is t...
Given that it does compile, it will still only be called with the argc and argv arguments. So your fooDouble will get the pointer value of argv, and FooVar will get whatever value is in that register/stack space used for that argument position (which may not have been initialized by the callee, so it may hold any und...
I wrote the following program: ``` #include<stdio.h> int main(void) { float f; printf("\nInput a floating-point no.: "); scanf("%f",&f); printf("\nOutput: %f\n",f); return 0; } ``` I am on Ubuntu and used GCC to compile the above program. Here is my sample run and output I want t...
Because the number 125.1 isimpossible to represent exactly with floating-point numbers. This happens in most programming languages. Use e.g.printf("%.1f", f);if you want to print the number with one decimal, but be warned: the number itself isnotexactly equal to 125.1.
I am doing some experiments to find out the ceiling of my requests per second rate of haproxy and nginx on RHEL or Centos. Part of my setup in nginx uses embedded LUA in the form of LuaJIT. My question is this: Does anybody have any experience or advice about the usefulness of doing some testing of these apps after ...
Experiments at a previous employer showed that the standard Linux and Solaris malloc/free implementations were not particularly efficient in high-concurrency multicore environments. We realized significant performance improvements by creating a custom allocator. I think it is definitely worthwhile to do experiments wi...
I have many times come across the statementchar* ch = "hello";. I understand thatchar* chtells thatchis a pointer towards achar. But what does assigninghelloto ch mean ? I cannot undestand this ? please help.
It meanschis a pointer to a character. When you dochar* ch = "hello"chwill be pointing to the first character i.e. characterh. To point to the second character, you can doch + 1orch[1]. Note that ideally the type ofchshould have beenconst char*as you can not write to the pointed memory location.
Suppose that I have used afree()function to free a memory that,for many reasons, I'm not allowed to. How can I stop my C application from crashing and just generate an error and continue the execution? I don't have try-catch kind of provision here (like C++/java...). Is there any way to ignore this error and continue ...
It's certainly not advisable. Even if your program's version offreecorrectly detects that the memory you're trying to free cannot be freed, and thus doesn't do any harm itself, you still have a bug in your program — part of the program thought it owned that memory. Who knows what it might have tried to do with that me...
I had modified make file as ``` linux: $(CC) mongoose.c -shared -fPIC -fpic -m32 -o $(LIB) $(LINFLAGS) $(CC) mongoose.c main.c -m32 -o $(PROG) $(LINFLAGS) ``` But when I run ld on mongoose I gets. I am getting warning that it is incompatible with i386 ``` ld mongoose ld: warning: i386 architecture of inpu...
ld is trying to create an x86-64 executable from your x86-32 object files, and is unhappy because that isn't something that makes sense. Use GCC to link instead of ld, passing the -m32 at link as well, and it will call the linker with the correct flags for linking x86-32 binaries.
What the...argument means in the declarationstatic void info(const char *fmt,...)? It's part of anClibrary I recently started to use. Sorry if it's basicCstuff but I never saw that before and google is not so verbose about...!
It means variable arguments, which means the compiler will accept and compile calls to it with any arguments. Usually their types are indicated by values in preceeding arguments.
So I found Tk alikeGNOCLfor linux Gtk. I wonder if there is any alike Tk libraries using windows native buttons and other components for tcl? (the more its api looks like Tk the better.) Is there any su
Tk 8.5 has native look & feel support through theTiletheme engine, renamedTtk. If you're not using very exotic Tk features, it should be possible to replace Tk with Ttk in your application and get native looks, keyboard bindings, etc.
I have an xml like file and I have to read only a part of the file.(subfile). Then I have to search this subfile for some "strings". I thought of reading a file from a start pointer till an end pointer(which would be the subfile). Then I should work with this subfile and inspect line by line of the subfile using fget...
You can usemmap()on UNIX/Linux to map a file to memory. This should make it easier to isolate a part of the file and work with it. Your xml library will probably want a buffer if it parses raw data, so you can just pass it the mmap result. Here is an excellent example of usage http://www.cs.purdue.edu/homes/fahmy/cs...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago. I am searching for some information...
sys/types.h: "data types" sys/socket.h: "main sockets header" sys/un.h: "definitions for UNIX domain sockets" unistd.h: "standard symbolic constants and types"
for example I can do ``` int *arr; arr = (int *)malloc(sizeof(int) * 1048575); ``` but I cannot do this without the program crashing: ``` int arr[1048575]; ``` why is this so?
Assumingarris a local variable, declaring it as an array uses memory from the (relatively limited) stack, whilemalloc()uses memory from the (comparatively limitless) heap.
I currently use c language to process the http event, and I need to do the SQL operation with mysql, then how to prevent the SQL injection, is there any c library for that,thank you?
SQL Injection Attacks and Some Tips on How to Prevent Them
I just installed omnicomplete plugin, does it support header auto completion? When I typed#include <, is it possible to provide a list of header files to complete? Many thanks!
You can just use thevim autocompletefeature, which was introduced in vim7. Just type in first few characters and pressCtrl->P(for backward search)orCtrl->N(for forward search), vim lists down all options available or completes it. And Yes it works even for header files. To make this work you should installctagsInus...
When I try to compile this code: ``` #include <stdio.h> main(int argc, char *argv[]) { double y = 0; __asm__ ("fldl $150;" "fsqrt;" "fstl %0;" : : "g" (y) ); printf("%f\n", y); return 0; } ``` I get this error: ``` sqrt.c: Assembler messages: sqrt.c:6: Error: suffix or opera...
I do not know of an assembly language which supports literal floating point constants for immediate use. The usual means is to declare initialized storage containing the floating point constant and referencing it: ``` const1: dq 1.2345 ... fldl const1 ``` For the example you give, it is possible to do ...
``` void main() { printf("ABCD"); printf("\n"); printf("ABCD" +1); printf("\n"); printf("ABCD" +3); } ``` Outputs is: ``` ABCD BCD D ``` Can anyone explain me why?
"ABCD"is actually an array of characters{'A','B','C','D', '\0'}(where'\0'is the trailing null byte). If you add 3 to that, then that is the equivalent of advancing a pointer 3 bytes forward from A, so you end up pointing atD. Question6.2 in the C FAQhas a picture that makes this clearer. The array decays to a point...
How bad is it to use a built-in object, type or whatever as something it's blatantly not, even if it performs in exactly the way you need? Assuming it's clearly commented what you're doing. For example, to use a single CGPoint to represent a start and end point on a single line. Should I really be defining my own ide...
For type safety, you should be defining your own. Also remember you can't dosomeRange.startorsomeRange.end. Rather, it would be the inscrutablesomeRange.xorsomeRange.y.
what will be the output of the following code : ``` char peer_ip[16]; inet_pton(AF_INET,"127.0.0.1",peer_ip); ``` now I have peer_ip in network form. How can I check what is the address family ??? I cannot use inet_ntop now. Is there any way ?? Will getaddrinfo work in this case ???
You can't—inet_ptongives you either astruct in_addr(forAF_INET) or astruct in6_addr(forAF_INET6), depending on what address family you pass in. If you consider these structures to be binary blobs of memory, there's no way you can recover the address family from them, you just have to keep track of what type of binary...
I'm starting out a program in SDL which obviously needs to load resources for the filesystem. I'd like file calls within the program to be platform-independent. My initial idea is to define a macro (lets call it PTH for path) that is defined in the preprocessor based on system type and and then make file calls in the ...
TheBoost Filesystem moduleis probably your best bet. It has override for the "/" operator on paths so you can do stuff like... ``` ifstream file2( arg_path / "foo" / "bar" ); ```
Just curious to know (as we use these functions often). I don't see any practical difference betweenstrncpy()andmemcpy(). Isn't it worth to say that effectively, ``` char* strncpy (char *dst, const char *src, size_t size) { return (char*)memcpy(dst, src, size); } ``` Or am I missing any side effect? There is one s...
There is a difference, see this part of thestrncpypage you linked to (emphasis mine): Copies the first num characters of source to destination.If the end of the source C string(which is signaled by a null-character)is found before num characters have been copied, destination is padded with zerosuntil a total of num c...
Using the openssl command line is possible to extract, in a human readable mode, all the information contained in a .pem certificate; that is: ``` openssl x509 -noout -in <MyCertificate>.pem -text ``` What are the suitable steps in order to extract this information using the openssl API?
TheX509_print_exfamily of functions is your answer. ``` #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/bio.h> int main(int argc, char **argv) { X509 *x509; BIO *i = BIO_new(BIO_s_file()); BIO *o = BIO_new_fp(stdout,BIO_NOCLOSE); if((argc < 2) || (BIO_read_filename(i, arg...
[how to use ~ operator ] I have a structure sayAlpha. I know the value of element insideAlpha(saya) which can be0or1- I want the other element of same structure to take inverse value of Alpha.a. For example: ``` if Alpha.a = 1 then Alpha.b = 0 ``` and vice versa I have tried: ``` Alpha.b = ~ (Alpha.a) ``` But u...
In C,trueis represented by 1, andfalseby 0. However, in a comparison, any non-false value is treated is true. The!operator doesbooleaninversion, so !0 is 1 and !1 is 0. The~operator, however, doesbitwiseinversion, where every bit in the value is replaced with its inverse. So ~0 is 0xffffffff (-1). ~1 is 0xfffffffe (...
I recently spent many hours trying to fix a problematic ld script. Once I had drawn (on paper) all the different sections I could figure out the problem. So I started searching for some sort of LD script generator, but could not find any! Does anybody know if such a tool exist? Something that can import/export ld scr...
To my knowledge, there are no non-proprietary tools for this purpose.
This question already has an answer here:Closed12 years ago. Possible Duplicate:What does the : do in a struct declaration after a member I would like to ask why the:character was added in this struct: ``` typedef union A { struct { ubyte B:4; } } struct_a; ``` Thanks in advance;
The:4is putting a 4-bit limit on the variable. See Section 6.9 of Kernighan & Ritchie.
Is there any way to find out whether an address supplied tofree( )is an invalid address, before calling thefree( )? We knowfree( )creates an undefined behaviour if the address is an invalid address (already freed address). So how to make sure that address is a valid one? Thanks in advance.
If you need to do this, you have a bigger problem -- you have free'd your memory before you've finished with it, or you've not invalidated references to memory when you've finished with it. Rather than trying to stop your program double-freeing by changingfree(), you should be trying to fix your pointer lifetime issu...
On Windows Sleep(0) yields thread control without specifying a minimum time, (see here) But on Linux and POSIX sleep(0) from unistd.h is just ignored. What's the best way to get Sleep(0) like behaviour in Linux?
Trysched_yieldfrom "sched.h", that is created just for what you want to do. If that doesn't work for whatever reason - tryusleep(1)- That will yield at least 1 microsecond delay (may be more), which in turn triggers a context switch (if any thread is waiting).
I have quite a large piece of code, that works well in a development version, with manyassert()in the code. I disabled assertions with-DNDEBUGdirective passed to g++, and now my code breaks with seg. fault. Is there something I don't know about assert()?
The most common issue with assert to my knowledge is having code with side effects within the assert itself. When you compile with -DNDEBUG asserts are essentially commented out, and thus code inside the assert isn't executed. The assert man page mentions this in the bugs section: ``` BUGS assert() is imple...
How do I get the local IP address before usingsendto()that is going to be used for the transmission to a remote host? If I understand correctly, it should be known already aftergethostbyname(remoteHostname)call. I need this for including the local IP in the transmitted packet (127.0.0.1 wouldn't make sense). UDP is ...
Try callinggetsockname(2)on a connected UDP socket; the stack would need to perform a fair amount of routing to connect the socket, sufficient to know which local address would be used once packets are sent or received.
I saw this function in some code and I can't find documentation on google about it. Can someone explain what it does and are there any alternatives to this ? Thanks.
Seehttp://msdn.microsoft.com/en-us/library/tsbaswba%28VS.80%29.aspx: it is a generic name forsscanf_s. EDIT: which is conveniently documentedhere._stscanf_sis in TCHAR.H on Windows platforms. You can probably get away with usingsscanf_sorswscanf_s.
I was planning to program in c using cygwin on windows. Does this have any performance drawbacks when compared to using gcc in ubuntu?
I've used Cygwin on Windows 7 and Windows 2008 R2 for C development. The experience was painful: not only slow, but Inever didmanage to get my preferred editor (Emacs) working properly in Cygwin. You could try a live distro of Linux that you could boot from a USB memory stick. That way you could program in C to you...
I'm writing a command-line program in C, and I'd like to implement a--helpoption to show the usual stuff like available options and what they do, and usage examples. Is there a proper method for formatting the text that is displayed in the help? Or do I just do my best to make it look nice? I looked at some random ...
Generally speaking more people are concerned that the program works as stated than how well the help is displayed. Do your best (effort is always appreciated) with printf and get on with it and your life. You have bigger fish to fry.
I'm working with a lexer that acceptsFILE*objects to read data from. I'd like to be able to pass it POSIX file descriptors (i.e. stuff you get fromopen, pipes, etc.). How can I turn a POSIX file descriptor into aFILE*?
On any POSIX-compliant system, you usefdopen().
This quicksort is supposed to sort "v[left]...v[right] into increasing order"; copied (without comments) from The C Programming Language by K&R (Second Edition): ``` void qsort(int v[], int left, int right) { int i, last; void swap(int v[], int i, int j); if (left >= right) return; swap(v, le...
Yes, you're right. You can useleft - (left - right) / 2to avoid overflows.
I want to print out into my sorted treeon which level this number wasand that must be arecursionfunction. Here is my code: ``` void printout(KNOTEN *start) { if (start == NULL) return; printout(start->left); printf("%d\n", start->number); printout(start->right); free(start); } ``` He...
I would modify it to this: ``` void printout(KNOTEN *start, int depth) { if(start == NULL) return; printout(start->left, depth+1); printf("%d(%d) \n",start->number, depth); printout(start->right, depth+1); free(start); } ```
Where can I find the code for malloc my gcc compiler is using at the moment? I actually want to write my own malloc function which will be a little different from the original one. I know I can use hooks et all, but I want to see the real code.
The POSIX interface of malloc isdefined here. If you want to find out how the C library in GNU/Linux (glibc) implementsmalloc, go and get the source code fromhttp://ftp.gnu.org/gnu/glibc/or browsethe git repositoryand look atthemalloc/malloc.cfile. There is also the base documentation of theMemory Allocator by Doug ...
I want to use a byte variableito execute a bit of code 256 times. The line below loops indefinitely, is there a tidy alternative that would work? ``` for (i = 0; i < 255; i++){ ``` Hopefully without using: a 16 bit variable, (or any extra bits at all)nested loopswhile(1)break;statements Thanks
``` i = 0; do { f(i); } while(i++!=255); ```
I am debugging some code and there is l_pid = 0 always for setting file locks.. It seems odd to me.. Is this correct?Documentation doesnt say about 0 zero value ..
l_pidis only meaningful when getting the lock status withF_GETLK; when setting a lock, if it succeeds then you know what pid owns it. :) (And the buffer is returned unmodified it it fails.)
I have this function: ``` void receive_message(int sock, char buffer[]) { int test = recv(sock, buffer, strlen(buffer), 0); buffer[test] = '\0'; } ``` the third argument of the functionrecv()is not working. apparently i cannot usestrlen()because the buffer don't have a\0.sizeof()didn't help me either. i'm w...
You're hoping in vain; C arrays don't have that much structure. You need to pass the size yourself.
I have the following C files in windows XP. optBladWriter.c optWriteNlpEmpsFile.c I would like to generate DLL for this code. I used the command add_library . My make file has the following : ``` CMAKE_MINIMUM_REQUIRED ( VERSION 2.6) add_library (optFmg optBladWriter.c optWriteNlpEmpsFile.c) ``` after running CMake ...
As documented, the default type of library is determined by theBUILD_SHARED_LIBSvariable. You can explicitly request a shared library with: ``` add_library(yourlib SHARED file.c ...) ```
I have to write a function that accepts a variable number of arguments, similar to the open() function ``` int open (const char *filename, int flags[, mode_t mode]) ``` I had a look at the va_list functionality, but how can I find out how many arguments the user has supplied? I dont want to have a parameter in the f...
You cannot. The caller must either supply a trailing sentinel argument (e.g. a0), or explicitly tell the function how many arguments to expect (e.g. the format fields inprintf).openknows to expect the third argument because you will have set theO_CREATflag in theflagsargument.
In C, you have to declare the length of an array: ``` int myArray[100]; ``` But when you're dealing withchars and strings, the length can be left blank: ``` char myString[] = "Hello, World!"; ``` Does the compiler generate the length for you by looking at the string?
This is not unique tochar. You could do this, for instance: ``` int myNumbers[] = { 5, 10, 15, 20, 42 }; ``` This is equivalent to writing: ``` int myNumbers[5] = { 5, 10, 15, 20, 42 }; ``` Initialising achararray from a string literal is a special case.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago. I want to calculate trigonometric r...
If the question is how to sum up the series, you could just update the term one by one: ``` double sum_the_series(double x, size_t number_of_terms) { const double x2 = x * x; double term = x; double result = term; for (size_t i = 1; i < number_of_terms; ++i) { term = term * x2 / (double(2*i) * double(...
I'm trying to read a simple text string from a website into my LabWindows CVI program. I've looked everywhere but can't find an example of using a simple HTTP GET request. Does anyone know if this can be accomplished in LabWindows? Here's the website text I'm trying to read:http://www.swpc.noaa.gov/ftpdir/latest/wwv...
Got it. LabWindows allows this kind of functionality through Telnet services. First you do a "InetTelnetOpen" to open the connection.Then you do "InetTelnetWrite" and write the "GET ..." message.Then you do "InetTelnetReadUntil" and read until the string "/html>" to get all the site's text. LabWindows truly is an aw...
I am reading a ring 0 privilege acquiringsource codein windows XP in that code, there are 2 lines which are ``` LONG (NTAPI *NtSystemDebugControl) (int,void*,DWORD,void*,DWORD,DWORD*); *(DWORD*) &NtSystemDebugControl =(DWORD)GetProcAddress(LoadLibrary("ntdll"),"NtSystemDebugControl"); ``` it is first time I...
The first line creates a function pointer, the second one initializes the function pointer in a rather horrible way (It will fail on 64-bit machines, though that is probably insignificant in this case). If you're asking whatGetProcAddressdoes I suggest reading about it inMSDN.
I have quite a large piece of code, that works well in a development version, with manyassert()in the code. I disabled assertions with-DNDEBUGdirective passed to g++, and now my code breaks with seg. fault. Is there something I don't know about assert()?
The most common issue with assert to my knowledge is having code with side effects within the assert itself. When you compile with -DNDEBUG asserts are essentially commented out, and thus code inside the assert isn't executed. The assert man page mentions this in the bugs section: ``` BUGS assert() is imple...
How do I get the local IP address before usingsendto()that is going to be used for the transmission to a remote host? If I understand correctly, it should be known already aftergethostbyname(remoteHostname)call. I need this for including the local IP in the transmitted packet (127.0.0.1 wouldn't make sense). UDP is ...
Try callinggetsockname(2)on a connected UDP socket; the stack would need to perform a fair amount of routing to connect the socket, sufficient to know which local address would be used once packets are sent or received.
I saw this function in some code and I can't find documentation on google about it. Can someone explain what it does and are there any alternatives to this ? Thanks.
Seehttp://msdn.microsoft.com/en-us/library/tsbaswba%28VS.80%29.aspx: it is a generic name forsscanf_s. EDIT: which is conveniently documentedhere._stscanf_sis in TCHAR.H on Windows platforms. You can probably get away with usingsscanf_sorswscanf_s.
I was planning to program in c using cygwin on windows. Does this have any performance drawbacks when compared to using gcc in ubuntu?
I've used Cygwin on Windows 7 and Windows 2008 R2 for C development. The experience was painful: not only slow, but Inever didmanage to get my preferred editor (Emacs) working properly in Cygwin. You could try a live distro of Linux that you could boot from a USB memory stick. That way you could program in C to you...
I'm writing a command-line program in C, and I'd like to implement a--helpoption to show the usual stuff like available options and what they do, and usage examples. Is there a proper method for formatting the text that is displayed in the help? Or do I just do my best to make it look nice? I looked at some random ...
Generally speaking more people are concerned that the program works as stated than how well the help is displayed. Do your best (effort is always appreciated) with printf and get on with it and your life. You have bigger fish to fry.
I'm working with a lexer that acceptsFILE*objects to read data from. I'd like to be able to pass it POSIX file descriptors (i.e. stuff you get fromopen, pipes, etc.). How can I turn a POSIX file descriptor into aFILE*?
On any POSIX-compliant system, you usefdopen().
This quicksort is supposed to sort "v[left]...v[right] into increasing order"; copied (without comments) from The C Programming Language by K&R (Second Edition): ``` void qsort(int v[], int left, int right) { int i, last; void swap(int v[], int i, int j); if (left >= right) return; swap(v, le...
Yes, you're right. You can useleft - (left - right) / 2to avoid overflows.
I want to print out into my sorted treeon which level this number wasand that must be arecursionfunction. Here is my code: ``` void printout(KNOTEN *start) { if (start == NULL) return; printout(start->left); printf("%d\n", start->number); printout(start->right); free(start); } ``` He...
I would modify it to this: ``` void printout(KNOTEN *start, int depth) { if(start == NULL) return; printout(start->left, depth+1); printf("%d(%d) \n",start->number, depth); printout(start->right, depth+1); free(start); } ```