question
stringlengths
25
894
answer
stringlengths
4
863
I am making a simple program which suppose to accept txt file data from clients. (not very big files..) I was wondering, if it is okay to create the threads using pthread instead of creating another process using fork. My plan is to create threads for every connection that I get to process the data and store it in a shared queue, which I can use mutex or semaphore to protect any race condition.
Yes, it is perfectly fine to use separate threads to process client connections. It will be faster compared to forking new processes. There is a drawback though in terms of isolation: because all clients are handled within the same process if this process goes down the server will not be able to serve other clients.
I started a new Win 32 console application project in VS2010.. It is known that you cant add reference to dll from references tabs, as Projects tab appears only... Under linker project properties i can see that i am able to specify only .lib files not dll. I have the header file and dll and lib but i want to use dll. Is it imposible to use dll with this type of project??
The linker doesn't know how to use a native DLL. The import library for the DLL is required.
I am using a loop to read message out from a c Berkeley socket but I am not able to detect when the socket is disconnected so I would accept a new connection. please help ``` while(true) { bzero(buffer,256); n = read(newsockfd,buffer,255); printf("%s\n",buffer); } ```
The only way you can detect that a socket is connected is by writing to it. Getting a error onread()/recv()will indicate that the connection is broken, but not getting an error when reading doesn't mean that the connection is up. You may be interested in reading this:http://lkml.indiana.edu/hypermail/linux/kernel/0106.1/1154.html In addition, usingTCP Keep Alivemay help distinguish between inactive and broken connections (by sending something at regular intervals even if there's no data to be sent by the application). (EDIT: Removed incorrect sentence as pointed out by @Damon, thanks.)
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this question We all know that C compilers spit out assembly. However I am doing research where my tool only accepts a narrow subset of ANSI C. Is there any C-to-C translators out there that can inline functions or flatten struct's, but writes out C code? Any other tool that could simplify C code, let me hear them.
LLVM supports something like this.
I have.libfile compiled from C code. How I know if this self-contained static library or just an import lib and DLL will be needed at runtime? Is there somedumpbinoption I'm missing?
Use the lib command. If it's static, lib will show you a pile of .obj files inside. Not so if it's an implib. ``` lib /list foo.lib ``` will do it. Also see: https://learn.microsoft.com/en-us/cpp/build/reference/managing-a-library
Since you're not reading from the stream it seems much more flexible. Both to mention that since you can easily change the timing/code location of the reads then you can with a c stream(am I wrong, can you make strings, ect into cFILE *streams)? Plus, I don't know I just feel a bit odd aboutscanf. Any pros/cons toscanfwould be appreciated. Edit: I meant the use of scanf or fscanf vs the combo of fgets+sscanf
This is well addressed in theC FAQ. Why does everyone say not to use scanf? What should I use instead? If you are reading from a trusted file (NOTstdin), there's no point in usingfgets + sscanfinstead offscanf. Indeed usingscanf(reading fromstdin) is problematic.
This question already has answers here:Closed12 years ago. Possible Duplicate:In C arrays why is this true? a[5] == 5[a] ``` int a[5]={1,2,3,4,5}; int i=4; printf("%d",i[a]); ``` Why do a[i] and i[a] refer to same location in the array?
This is because array subscript iscommutative(it's an addition), the order can be swapped : ``` a[i] = *(a + i) i[a] = *(i + a) *(a + i) = *(i + a) a[i] = i[a] ```
I have installed mingW to use gcc, platform windows 7. I am trying to locate the standard C library libc.a in mingW folder. no luck.. is it stored in some other name?
MinGW does not build against glibc, it builds against msvcrt. As such, it uses libmsvcrtXX.a instead.
If I have two or more computers on a LAN communicating via UDP, do they all have to be using the same port to be able to receive messages from one another? For example, say my desktop is using port 1550 to send a message and my notebook, which is also on the LAN, is using port 3746 to listen for and receive messages. Would sending using just the destination IP in such a situation work? If not, would each computer have to know and specify the receiver's port?
For a UDP or TCP endpoint an address and port must be set. The initiator must know what address-port to send to. The receiver can use the getpeername() call to determine the address-port combination of the sender and then use this information to build up the address structure for a reply message. The two do not need to use the same port number.
I have the following example in C: ``` int x = 123; size of int = 4 bytes. hex value = 7b binary value = 0111 1011 ``` What will be the hex/binary value if my x was a char? ``` char x = 123; size of char = 1 byte. hex value = ?? binary value = ?? ```
Sincecharis smaller thanint, it would be the same. Except for leading zeros you would find in anint. Try this: ``` 6 int x = 123; 7 8 printf ("Size of int is %d bytes\n", sizeof(int)); 9 printf ("Size of char is %d byte\n", sizeof(char)); 10 11 printf ("Hex value is %x\n", x); 12 printf ("Hex value is %x\n", (char)x); 13 14 printf ("As for binary value .... google is your friend\n"); ``` Output is: ``` Size of int is 4 bytes Size of char is 1 byte Hex value is 7b Hex value is 7b ``` As for binary value .... google is your friend Thissiteseems to explain things well
Say I have two programs X and Y asking for input fromstdin. X and Y are run usingfork()followed byexecve()from a third from say A. What is happening is X is scheduled first. When X reaches the scanf statement, Y gets scheduled and X never gets an input. How do I take care of it?
HaveAmediate the input forXandY.Acan create a pipe to and from each child process. It can read a prompt from a pipe, write the prompt to standard output, read the response from standard input, and write the response to the pipe for the child process.
I would like to use 'const' in C interface functions to note that certain char * arguments are not modified by the function. What trouble might this cause in porting this code to various platforms? Is support of 'const' in C code pretty standard? When did this become officially in C standard?
I can't imagineconstnot being supported by any compilers, so porting should be a non-issue. If youwereto find such a beast, you could just put ``` #define const ``` Somewhere in a common header file to make all of theconstkeywords vanish. The runtime semantics of your program won't change at all (since your compiler didn't support the keyword anyway).
I am planning to write a mobile application (iOS and Android) where there is a lot of image recognition processing. Is it a good solution to write the image recognition code in C or C++ to reuse it in both platforms ? Will there be a lot platform specific C/C++ code that makes writing and maintaining it unjustified ? Note: This application is based on image recognition and the biggest part of the code is for image recognition.
I would say yes. This is the kind of thing I believe the Android-NDK is best used for and since straight C compiles fine from OBJ-C, there could be a lot of code reused between the two platforms.
I have a very simple C code in which I am trying to use OpenGl. When I include the following files ``` #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <stdlib.h> ``` I get the following error(and many more but they are similar): C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\include\GL/gl.h(1152) : error C2144: syntax error : 'void' should be preceded by ';' but when I include ``` #include <windows.h> #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <stdlib.h> ``` I get the following error \mainfile.cpp(4) : fatal error C1083: Cannot open include file: 'GL/glut.h': No such file or directory any idea what is happening? I am using XP, VS2005
GLUT isn't part of OpenGL. You need to install it, which is what that error says.
I'm creating a simple midi based game in C and I am wondering if there are any libraries to load a midi file, play and also manipulate it by getting the note values. Thanks in advance!
Check SDL. More especifically,SDL_mixer. Description:SDL_mixer is a sample multi-channel audio mixer library. It supports any number of simultaneously playing channels of 16 bit stereo audio, plus a single channel of music, mixed by the popular MikMod MOD, Timidity MIDI, Ogg Vorbis, and SMPEG MP3 libraries.
I'm taking a Computer Systems class as a pre-req for my Masters and came across something I found fascinating and hard to see practical use of and that is "faking subtraction" and the fact that there doesn't need to be a subtraction instruction. Something like: x - y Can be written as: x + (~y + 1) Now, that's all well and good but it seems like that is overly complicated for a simple subtraction, especially when you could just easily put "x - y". Are there situations where it would be necessary to do this, or is it just something that CAN be done but isn't.
This is often how it's done at the hardware level (i.e. inside the ALU). At the software level, it's generally useless, as it can never be more efficient than the straightfoward subtraction (unless you have a truly bizarre compiler/platform combination).
I am doing a GTK C program on Windows and I want to prevent the user from being able to select/highlight any rows in the tree view. Can anyone point me in the right direction?
The "gtk_tree_selection_set_select_function ()" seems to be exactly what you want. http://developer.gnome.org/gtk/2.24/GtkTreeSelection.html#gtk-tree-selection-set-select-function
This question already has answers here:Closed12 years ago. Possible Duplicate:Is there a printf converter to print in binary format? Here is my program ``` #include<stdio.h> int main () { int i,a=2; i=~a; printf("a=%d\ni=%d\n",a,i); return 0; } ``` The output is ``` a=2 i=-3 ``` I want this to print in binary. There are %x, %o, and %d which are for hexadecimal, octal, and decimal number, but what is for printing binary in printf?
printf() doesn't directly support that. Instead you have to make your own function. Something like: ``` while (n) { if (n & 1) printf("1"); else printf("0"); n >>= 1; } printf("\n"); ```
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this question I want some library (API) to open, seek, read, write ... (in one wordto process) gzip files. Is there any open-source cross-platform ones for C or C++?
Yes.Zlibis the one. There is alsothis related questionon how to process gzip files more easily and conveniently in C++. The most notable and up to date suggestion seems to be theGZip filters in Boost.IOStreams, which I have good experience with myself.
I am wondering how to add the new line before closing the file. I have tried usingfputsandputsand frpints something likeputs("/n");etc but it doesnt work. Thanks & regards, SamPrat
a very simple way, no error checking: ``` FILE * file = fopen(fname, "a"); fwrite("\n", strlen("\n"), 1, file); fclose(file); ```
I am a beginner in C, and i would like to read how various libraries are implemented. I looked under /usr/src/include and all i found was .h files. For example , i was looking at malloc.h and all that it does is , declare extern functions. So i am trying to find the source for those functions. I downloaded gcc source rpm, but looking at the gcc source, it looks more like compiler code,rather than code for libraries such as stdlib. Can you please help me by pointing me to the right direction. Thank you.
You need to get the source code of the associated C library, probablyglibcoreglibcin your case. In the /usr/include/ folder, only the headers of the libc are present, along with some linux kernel headers in the linux/ subfolder.
I am working on a project which involves stereo-vision. I am using c and openncv right now. I want to make a 3D plot of points based on their calculated position. Can someone tell how to do it in c or opencv? platform: XP, visualstudio 2005
You need a 3D rendering engine like OpenGL or DirectX. You can use any of them in VS2005 and WindowsXP.
was wondering if an Equivalent of PHP'sstripslashes()in C existed?
No, because this is not a problem that is usually encountered in C. If you want the same functionality then you will need to write it yourself, or find some library that provides it.
I am using c string library's strlen function.I passed a NULL string to it and found mysterious result.I know I am not supposed to pass NULL string but I need an explanation for it.The code looks something like this ``` main() { int k; char *s=NULL; strlen(s); // k = strlen(s); } ``` On my gcc compiler ,It runs fine with the comment. but if you will remove the comment in the linek=strlen(s); it produces segmentation fault. Any explanation ?
The first 'strlen' call that is not assigning its return value is probably being optimized out by your compiler.
Hi I am trying to use C to parse xml, but all the examples I can find are using a file to get the xml, I have the xml already loaded into a variable and I want libxml2 to take the xml from there instead of a file.... but I can't figure out how! Any help would be appreciated thanks
Have a look atthis example:usingXmlReadMemory
I wanted to try out a more complex example of allocating memory with new in an object and allocating further inside it, but needed to know for sure when a stackoverflow will happen. So decided to trythisexample. I called thefoo()function frommain()and expected it to give a stackoverflow error. It didn't. In foo, I increased the array size by a few more zeros and added 40 more such array declarations in foo. Still didn't crash.Am using gcc version 4.4.2 20091027 (Red Hat 4.4.2-7) (GCC). Shouldn't a stack allocation of approx more than 1MB give a stackoverflow error? ``` void foo() { double x[100000000]; double x1[100000000]; double x2[100000000]; double x3[100000000]; double x4[100000000]; //...and many more } int main() { foo(); } ``` Compiled as gcc -o test test.c
Make foo call itself recursively, and have some counter increment with each call. You'll get your fault soon enough.
I have been asked in an interview how to count the number of nodes in a linked list without traversing the list? Is there any way to achieve this?
The only way I can think of is to add a counter of the number of nodes which is incremented each time theaddorinsertmethods are invoked, and decremented whendeleteis invoked. You cannot make assumptions about memory occupied because, being a linked list, you cannot guarantee that all nodes will be in the same memory block (indeed, this is highly improbable).
I declared an array and take input from user. Now i want to check duplicate entries, they have to be deleted and memory should be freed. Is it possible to free memory. freeing the unused memory and reducing the array size? I entered[10,21,3,4,4,2,6,7,21,4,10].it should get truncated as[10,21,3,4,2,6,7]and array length should now be 7,and i don't want to use sorting.
In C, you cannot change the size of an array. If you use dynamically allocated memory (withmalloc()), you can userealloc()to resize the memory region, or allocate a new region, copy the data into it and free the old one. A solution that is often acceptable is to simply leave part of the array unused. This is done by recording how many entries are used in a separate integer variable.
I wrote following program ``` int main () { char a=0xf; a=a+1; printf("%c\n",a); } ``` the output of above program is what I am not able to understand.It is giving me some character which I am not able to understand.Is it possible to find out ASCII code of the character that I am getting in my above program so that I understand what is it printing. EDIT Based on the replies I read I am adding further to my confusion if I write a statement as following char ch='Z'; then what would be stored in ch, 1) The character Z2) ASCII value of Z3) Z along with single inverted commas4) Both (1) and (2)
ASCII value for 16(0x0f + 1 = 0x10) isDLE (data link escape)which is non-printable character. Just Print as integer like this. ``` printf("%d\n",a); ```
Is there any pre-defined flag by standard specification (ANSI/C89/C99) for debug-mode-compilation in C compiler? I knowDEBUGandNDEBUGflags, but I am not sure about whether they're in the C standard or not.
That really depends on what you call - "debug mode compilation". It can mean lots of different things to different people: no optimizations, so code can be more easily debuggeddebug symbol generation, again to help debuggerusage ofassertfunctioncompiling with debug libraries, that do additional runtime checkingusage of other custom debugging techniques TheNDEBUGcontrols the bullet #3 only. Of course it is often combined with others, because it makes sense to use them together. But nothing forces you to use all of them - you may define various combinations of these things, e.g. optimized build with assert checks, etc.
I want to write a c program that keeps reading a file and whenever a new line is added to that file, its sent across network (lets assume via tcp) to recipient. What is the best way to do it? o keep the file open and do something like tail -F on it to keep reading? o read file on my own? I am not worried about sending on network part, I need to have best way of getting a new line out of the file. On that line I might do some filtering too before sending.
Linux hasinotify, OS X haskqueue/kevent, Windows hassimilar stuff. All of these let your process block until the kernel notifies you of a change to the file. This is very efficient because your process can sleep until a change actually happens, but obviously these interfaces are not portable. The only portable approach is to poll the file periodically to see if it changes, but obviously that is not as efficient.
Ok... So I had a silly idea and tried putting the value 0123 into an int, just curious to see what would happen, I assumed that when I printed the value I'd get 123, but instead I got 83... Any ideas why? what happens inside the compiler/memory that makes this value become 83? I tried this in C++ and C with GCC compiler and also tried with a float which yielded the same results.
In C/C++ a numeric literal prefixed with a '0' is octal (base 8). Seehttp://www.cplusplus.com/doc/tutorial/constants/
Does anyone knows what signal Xcode sends to kill a running program? I need an handler to do some cleanup before the programs gets killed. I already tried SIGINT and SIGTERM but it doesn't seem to work.
It sends sinal SIGKILL. To verify you can open any application in debug mode and check the console when you stop the task. However if it is kill -9 you cannot trap the signal. What kind of clean up you want to do? I don't think there is any need to handle that event as you are doing it on purpose from XCode. If you are trying to send this signal to a process from outside Xcode like Terminal then in makes sense.
I have an old piece of software that uses gtkembedmoz, and I need to update it to run on ubuntu lucid, which does not provide that library. What API replaces the functionality that it provides?
You should useWebkitGTKthese days for embedding a web browser into a GTK program.
This question already has answers here:Closed12 years ago. Possible Duplicate:Do I cast the result of malloc? I just learned how to use the malloc function, and my teacher mentioned that it's necessary to make a type cast when passing the memory address to the pointer. For example, here's a code to get 16 new bytes allocated (4 ints) using malloc: ``` #include <stdlib.h> int main(){ int *p; p = (int *)malloc(4*sizeof(int)); return 0; } ``` My question: is the (int *) cast on the right side of the attribution necessary? After all p is already a pointer to ints, so the pointer arithmetic should work fine even without that cast. Thanks
You only need the cast if you are using malloc in C++ code. For C it's preferable tonotuse the cast as it is (a) unnecessary and (b) can mask problems that would otherwise be reported by the compiler.
I have code written in C. I want to get using C code information that is stored in routing table. Is it possible?
You can also run "strace route add ..." to see how theroutecommand does it. On my system, it usesioctlwithSIOCADDRT. A little searching turns up somesample code. Oddly, the best documentation I have found is fromIBM's AS400 man pages. If you just want to read the routing table, you can open and read/proc/net/route. (Again,straceshows that this is how theroutecommand does it.) The hex numbers are 32-bit IP addresses in machine-endian form. Trycat /proc/net/route.
Just want to know whether the casts in the example below are redundant. uint16_t basic_units = 4587U; uint8_t int_val = (uint8_t) (((uint16_t ) (basic_units * 5U)) / 1000U);
Theuint8_tcast is redundant. Theuint16_tcast may have the (un)intended consequence of truncating an intermediate value in the calculation ifbasic_units * 5Uwould overflow a normaluint16_tbefore being divided by 1000.
This question already has answers here:Closed12 years ago. Possible Duplicate:Selectively disable GCC warnings for only part of a translation unit? How to enable a specific gcc warnings for a specific directory or file ? I want to enable-Wsign-conversionfor my own files not for any other system headers
This line should do it: (seehere)#pragma GCC diagnostic warning "-Wsign-conversion" Put it in the affected files or in a header that is included in all you files
I would swear that I read somewhere that there's a way to cause GDI calls to treat x,y coordinates differently than the default. For instance, instead of x,y=0,0 being upper left, you could put 0,0 in the lower left, or any other corner. I've tried digging through my books, and it's too slippery to google effectively, at least with any of the words I've brought to bear. Anyone have any ideas how to do this?
Use SetMapMode to change this, MM_TEXT is closer to pixel coordinates, MM_METRIC, MM_LOMETRIC etc... are closer to paper coordinates and have an inverted y axis. See alsoGDI mapping modes explained
i am trying to find the select() source code (linux, i386 arch) in the glibc source code, but i cannot find anything (related to the said architecture) Could anybody point me to the select() source code ?
mh's answer is pretty good, but I will try to be more specific: select is Linux system call, not libc function. It's source code could be foundhere. libc has only wrapper for calling (executing) linux system call. Wrapper for select syscall is created on the fly at build time, because select is in syscalls.list file.
Following code does compile in gcc 4.5 but it is not being compiled in visual c 2005. ``` int main() { int len; len = 32; char buff[len]; return 0; } ``` I know that i am declaring array after statment, which is against ANSI C rules. But why GCC does not give any error or warning, and in visual c, it gives error like, ``` error C2143: syntax error : missing ';' before 'type' ``` any ideas? Thanks.
Your C code is not C90 compliant.gcc -pedanticwill warn about this. ``` ~/tmp$ gcc -pedantic a.c a.c: In function ‘main’: a.c:5: warning: ISO C90 forbids variable length array ‘buff’ a.c:5: warning: ISO C90 forbids mixed declarations and code ~/tmp$ ```
I am trying to allocate a shared memory of size 64B. But the compiler throws error when i give a size of more than 27.. How to solve this problem. I am using gcc compiler. I am running the program on a server. This is the code i used. ``` shmid=(shmget(key,size,IPC_CREAT | 0666)); // size is defined as 64 ``` I am getting an error saying memory allocation failed. But for size under 27 it works fine
Don't use SysV shared memory -- the interface is seriously awful, and has a number of huge drawbacks (e.g, there are tight limits on how much you can use, and it has to be cleaned up manually if your application crashes). If you need shared memory, usemmap().
i wanted an UDisks script to list all the usb devices that are mounted on my system , which must have ability to detect LVM devices. Perl / C / Shell any is fine Many thanks. P.S: Hal is deprecated on my Gentoo and removed
loads of info about udisks herehttp://igurublog.wordpress.com/2011/01/26/a-custom-udisks-automounter/
I have a simple argument list. And I just wanna print it to stdout, but I'm getting wired output before printing "end". Does anyone know where that empty line and unreadable characters come from?? output: ``` start hello hello2 hello3 hello 4 UH��AWAVAUATE1�S1�H��HH�E� end void printTest(const char* msg, ...) { va_list ap; int i; const char* curMsg=0; va_start(ap, msg); printf("start\n"); for(curMsg= msg ; curMsg!=0 ; curMsg = va_arg(ap, const char*)){ printf("%s\n", curMsg); } printf("end\n"); va_end(ap); } int main(){ printTest("hello", "hello2", "hello3", "hello 4"); return 0; } ```
How do you expect to read a null pointer to terminate the loop when you're not passing one? Change the call to: ``` printTest("hello", "hello2", "hello3", "hello 4", (char *)0); ```
I am trying to get theIClassvalues from registry key usingRegQueryVaueExand convert them to GUID for my application. I could do that forREG_SZsize, however, I am trying to figure out a way to do the same forIClassvalues with REG_MULTI_SZ that have more than oneIClass. It doesn't seem to be straightforward as characters between the values are not consistent. Sometimes, each value is delimited by a COMMA, sometimes the IClass value is equated to%b. Is there a simple way to achieve what I am looking for? Please suggest.
Looks like the best way to achieve this is to open the registry key of the driver withRegOpenKeyExand useRegEnumValueto get the IClass values (by passing IClass value name as parameter) in a loop (do-while) untilRegEnumValuefails. Thanks all for the comments and suggestions.
I want to combine both the for loops into single for loop. How can i do that? I want to loop through a to z, and A to Z, like so: ``` char ch; for (ch = 'A' ; ch <= 'Z' ; ch++ ) { } for (ch = 'a' ; ch <= 'z' ; ch++ ) { } ``` but using a single loop.
``` for (char ch = 'A' ; ch <= 'z' ; ch == 'Z' ? ch = 'a' : ++ch ) { } ``` Should work -- though please, please, don't inflict this on your fellow developers.
``` if(...) { ... } ``` It seems in the above case a;is optional,when is a semicolon after}necessary in c/c++?
``` int a[2] = {1,2}, j = 5; ``` When initialization of array or structure are done with{}all the subsequent variables are declared after,. Edit: As you changed your question;;is mandatory after theclass,enum,initializationsyntax declarations. ``` class A {}; // same for `struct enum E {}; // enum class (c++0x) int a[] = {1,2}; // array or object initialization ``` And as per comment by @rubenvb: ``` do {} while(condition); ```
``` typedef union epoll_data { void *ptr; int fd; __uint32_t u32; __uint64_t u64; } epoll_data_t; ``` Hereintand__uint32_tare 4 bytes,while the others are 8 bytes. When we setfdto anint,does it lie on the first 4 bytes or the last 4 bytes,or does it depend on endianness? Some reason is appreciated.
It lies on the first 4 bytes. From the C99 standard §6.7.2.1/14 (§6.7.2.1/16 in C11 and C18): The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit-field, then to the unit in which it resides), and vice versa. This implies that the address of all members of a union is the same.
i like to get float value with first two decimal value in C language. my input is ``` Float f; f=2.3678; ``` i like to get output like this ``` 2.36 ```
Include themath.hheader file and do this: ``` float f; f = 2.3678; f = floor(f * 100) / 100; // f = 2.36 ```
I have a coded a program in C for linux. At the moment I am using ubuntu upstart to run as a background service. I want to be able to have the program gracefully shutdown when commanded instead of just being killed off. Can someone please point me to the functions used to receive such a command? (edit: can't answer own post but it seems I am meant to use signal.h signal function to put callbacks onSIGTERMandSIGKILL).
You want to usesigaction(2)to define a handler to be run whenSIGTERMis caught.
I have char* data; which has a buffer dumped into it. I want to view the content of this char*. I do not know the size of this pointer data so How do I print it?! Thank you
Assuming thechar*isNUL-terminated, useprintf("%s\n",data);. If the data are notNUL-terminated, this may cause a segmentation fault. If your data have some format other than ASCII characters, you're going to need to write some code to print it.
I have set of WCF web services that I need to generate a Windows based test client. Does anyone know of a tool that will take as WSDL and auto generate some basic forms based on what is in the WSDL. Any thoughts as to how I can get a basic form with fields/labels without having to explicitly make a form. Any thoughts?
If this is for testing only I would suggest the excellentSOAP UItool and the free version is capable enough but only the pro version has a GUI based input. The other tool I have used briefly isWCF Storm. Otherwise take a look at this test client code that is very similar to what you wanthttp://www.larswilhelmsen.com/2008/10/04/wcf-test-client-extended/
Is it a guarantee thatstateafter this code will beLX_DONE? ``` enum lx_state { LX_START, LX_MIDDLE, LX_DONE }; enum lx_state state = LX_START; ++state; ++state; ```
Yes, the C standard says, in 6.7.2.2/3, Each subsequent enumerator with no = defines its enumeration constant as the value of the constant expression obtained by adding 1 to the value of the previous enumeration constant
This question already has answers here:Closed12 years ago. Possible Duplicate:Do I cast the result of malloc? I just learned how to use the malloc function, and my teacher mentioned that it's necessary to make a type cast when passing the memory address to the pointer. For example, here's a code to get 16 new bytes allocated (4 ints) using malloc: ``` #include <stdlib.h> int main(){ int *p; p = (int *)malloc(4*sizeof(int)); return 0; } ``` My question: is the (int *) cast on the right side of the attribution necessary? After all p is already a pointer to ints, so the pointer arithmetic should work fine even without that cast. Thanks
You only need the cast if you are using malloc in C++ code. For C it's preferable tonotuse the cast as it is (a) unnecessary and (b) can mask problems that would otherwise be reported by the compiler.
I have code written in C. I want to get using C code information that is stored in routing table. Is it possible?
You can also run "strace route add ..." to see how theroutecommand does it. On my system, it usesioctlwithSIOCADDRT. A little searching turns up somesample code. Oddly, the best documentation I have found is fromIBM's AS400 man pages. If you just want to read the routing table, you can open and read/proc/net/route. (Again,straceshows that this is how theroutecommand does it.) The hex numbers are 32-bit IP addresses in machine-endian form. Trycat /proc/net/route.
Just want to know whether the casts in the example below are redundant. uint16_t basic_units = 4587U; uint8_t int_val = (uint8_t) (((uint16_t ) (basic_units * 5U)) / 1000U);
Theuint8_tcast is redundant. Theuint16_tcast may have the (un)intended consequence of truncating an intermediate value in the calculation ifbasic_units * 5Uwould overflow a normaluint16_tbefore being divided by 1000.
This question already has answers here:Closed12 years ago. Possible Duplicate:Selectively disable GCC warnings for only part of a translation unit? How to enable a specific gcc warnings for a specific directory or file ? I want to enable-Wsign-conversionfor my own files not for any other system headers
This line should do it: (seehere)#pragma GCC diagnostic warning "-Wsign-conversion" Put it in the affected files or in a header that is included in all you files
I would swear that I read somewhere that there's a way to cause GDI calls to treat x,y coordinates differently than the default. For instance, instead of x,y=0,0 being upper left, you could put 0,0 in the lower left, or any other corner. I've tried digging through my books, and it's too slippery to google effectively, at least with any of the words I've brought to bear. Anyone have any ideas how to do this?
Use SetMapMode to change this, MM_TEXT is closer to pixel coordinates, MM_METRIC, MM_LOMETRIC etc... are closer to paper coordinates and have an inverted y axis. See alsoGDI mapping modes explained
i am trying to find the select() source code (linux, i386 arch) in the glibc source code, but i cannot find anything (related to the said architecture) Could anybody point me to the select() source code ?
mh's answer is pretty good, but I will try to be more specific: select is Linux system call, not libc function. It's source code could be foundhere. libc has only wrapper for calling (executing) linux system call. Wrapper for select syscall is created on the fly at build time, because select is in syscalls.list file.
Following code does compile in gcc 4.5 but it is not being compiled in visual c 2005. ``` int main() { int len; len = 32; char buff[len]; return 0; } ``` I know that i am declaring array after statment, which is against ANSI C rules. But why GCC does not give any error or warning, and in visual c, it gives error like, ``` error C2143: syntax error : missing ';' before 'type' ``` any ideas? Thanks.
Your C code is not C90 compliant.gcc -pedanticwill warn about this. ``` ~/tmp$ gcc -pedantic a.c a.c: In function ‘main’: a.c:5: warning: ISO C90 forbids variable length array ‘buff’ a.c:5: warning: ISO C90 forbids mixed declarations and code ~/tmp$ ```
I am trying to allocate a shared memory of size 64B. But the compiler throws error when i give a size of more than 27.. How to solve this problem. I am using gcc compiler. I am running the program on a server. This is the code i used. ``` shmid=(shmget(key,size,IPC_CREAT | 0666)); // size is defined as 64 ``` I am getting an error saying memory allocation failed. But for size under 27 it works fine
Don't use SysV shared memory -- the interface is seriously awful, and has a number of huge drawbacks (e.g, there are tight limits on how much you can use, and it has to be cleaned up manually if your application crashes). If you need shared memory, usemmap().
i wanted an UDisks script to list all the usb devices that are mounted on my system , which must have ability to detect LVM devices. Perl / C / Shell any is fine Many thanks. P.S: Hal is deprecated on my Gentoo and removed
loads of info about udisks herehttp://igurublog.wordpress.com/2011/01/26/a-custom-udisks-automounter/
I have a simple argument list. And I just wanna print it to stdout, but I'm getting wired output before printing "end". Does anyone know where that empty line and unreadable characters come from?? output: ``` start hello hello2 hello3 hello 4 UH��AWAVAUATE1�S1�H��HH�E� end void printTest(const char* msg, ...) { va_list ap; int i; const char* curMsg=0; va_start(ap, msg); printf("start\n"); for(curMsg= msg ; curMsg!=0 ; curMsg = va_arg(ap, const char*)){ printf("%s\n", curMsg); } printf("end\n"); va_end(ap); } int main(){ printTest("hello", "hello2", "hello3", "hello 4"); return 0; } ```
How do you expect to read a null pointer to terminate the loop when you're not passing one? Change the call to: ``` printTest("hello", "hello2", "hello3", "hello 4", (char *)0); ```
I am trying to get theIClassvalues from registry key usingRegQueryVaueExand convert them to GUID for my application. I could do that forREG_SZsize, however, I am trying to figure out a way to do the same forIClassvalues with REG_MULTI_SZ that have more than oneIClass. It doesn't seem to be straightforward as characters between the values are not consistent. Sometimes, each value is delimited by a COMMA, sometimes the IClass value is equated to%b. Is there a simple way to achieve what I am looking for? Please suggest.
Looks like the best way to achieve this is to open the registry key of the driver withRegOpenKeyExand useRegEnumValueto get the IClass values (by passing IClass value name as parameter) in a loop (do-while) untilRegEnumValuefails. Thanks all for the comments and suggestions.
I want to combine both the for loops into single for loop. How can i do that? I want to loop through a to z, and A to Z, like so: ``` char ch; for (ch = 'A' ; ch <= 'Z' ; ch++ ) { } for (ch = 'a' ; ch <= 'z' ; ch++ ) { } ``` but using a single loop.
``` for (char ch = 'A' ; ch <= 'z' ; ch == 'Z' ? ch = 'a' : ++ch ) { } ``` Should work -- though please, please, don't inflict this on your fellow developers.
I am new in Linux and system programming . I Want to write a c program which finds processes whose cpu% usage are more than a specific given value and sends them to background. anybody can help me ! I really appreciate it
I'm fairly sure that what you're asking is that you want to detect if a process is using X amount of CPU and if so, take it off the CPU for a while. There's a piece of software already that does this: It's called the kernel. I'm not aware of any way to programatically take another process off CPU unless that other program supports an external interface to reduce its load. Most likely what you really want to do is configure theniceand other scheduler parameters of the running process so the kernel is more like to to take it off CPU when another program needs to do work. But what underlying problem are youreallytrying to solve here? Maybe if you tell us that we can offer an alternate solution.
How can the following C function be wrapped with SWIG? ``` int add_option(const unsigned char *data); ``` Currently I get this wrapped to: ``` public static int add_option(SWIGTYPE_p_unsigned_char data); ``` Is it possible to wrap it for String, Byte[] or something similar?
``` %module Example %{ int func(const unsigned char *data); %} %include <arrays_java.i> %apply signed char[] { const unsigned char *data}; int func(const unsigned char *data); ``` Use this code !!!!!
this type of declaration of function is valid inCbut why not inC++? ``` int sum(i,j)int i,j; { return i+j; } ```
This is because that old-style function definition declares no prototype. That is, the caller would not know what parameter types the function expects. In C++, that's too much of a type safety miss. In particular, the FDIS says Change:In C++, the syntax for function definition excludes the "old-style" C function. In C, "old-style" syntax is allowed, but deprecated as "obsolescent."Rationale:Prototypes are essential to type safety.Effect on original feature:Deletion of semantically well-defined feature.Difficulty of converting:Syntactic transformation.How widely used:Common in old programs, but already known to be obsolescent.
I'm trying to figure out how to call a c function from an obj-c file. I've seen some good examples of how to do the opposite. In the example below I have an objective c file. It contains a c function named setup. I want to be able to create an instance of my obj-c file in the regular way and then call the setup function. Header ``` #import <Foundation/Foundation.h> void setup(int,float); @interface Test : NSObject { } @end ``` Source ``` #import "Test.h" #include <stdio.h> #include <stdlib.h> void setup(int val1,float val2) { //do something with values } @implementation Test @end ``` View did load ``` Test *test =[Test alloc]init] //this does not work test.setup(6,1.4); ```
Just call setup(). As declared, is in no way tied to an object - it's just a regular C function.
Is there a clean way to limit the number of hits from an SQLite3SELECTstatement? For example, I might query withSELECT * FROM myTable WHERE name='Smith';realising I could encounter thousands of hits. I'd like SQLite3 to give me say the first 10 it encounters and then terminate the query. How do I do this? If SQLite3 does not provide this immediately, is there anything I can edit in the SQLite3 source code from which I can rebuild? Assume I'm in an environment where I have only one thread and I'd like control back in a reasonable time.
You're looking for theLIMITclause: ``` SELECT * FROM myTable WHERE name='Smith' LIMIT 10 ```
I have one doubt in the following snippet. Actually I am initializing all the array index to zero in following code, but thisforloop is going infinitely. I found reason that we are trying to access the 26th index of array, so that value gets initialized to zero again since there is 0 to 25 index. So the for loop is going infinitely. Explain if any one the actual reason behind this stuff. ``` int array[26]; int i; for (i = 0; i <= 26; i++) array[i]= 0; ```
You have to usei < 26; otherwise you exceed the array bounds. Due to the layout of the stack on most systemsarray[26]will point to the memory used foriwhich results in the loop starting again since you loop body is setting i to 0 instead of an appropriate array element. Note that you can simply useint array[36] = { 0 };to create the array with all elements being set to 0.
If I understand right that global variables (which go into data segment) in C are initialized where auto variables (which go into stack) are not. or perhaps the other way round? Why is it so? What is merit of compiler not initializing both kind of variables? Does it increase speed etc?
As you say, global variables go in the data segment, so their value is contained in the final executable, and it might as well be an initialised value as there is no performance difference either way. On the other hand, local variables are allocated onto the stack, which is set up at run time, so initialising them would have a performance hit.
``` char p[]="abc\012\0x34"; printf("%d\n",strlen(p)); ``` I am getting output 4. Shouldn't it be 3 ??? Although for following i am getting 3. ``` char p[]="abc\0"; printf("%d\n",strlen(p)); ```
Your stringdoescontain four characters before the\0, i.e.abcand\012. The latter is a valid octal escape sequence, which is 10 in decimal, i.e an ASCII linefeed character. \0x34on the other hand isn't valid octal - only the\0part is valid hence that's the real end of your NUL terminated string.
This question already has answers here:Closed12 years ago. Possible Duplicates:checking for NULL before calling freeWhat happens when you try to free() already freed memory in c? Hope this isn't a totally dumb question. Anyway... What happens when a null pointer is passed tofree. Thank you! P.S. What about a standard compliant allocator? Thanks again!
It immediately returns without doing anything. Per 7.20.3.2, paragraph 3: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation.If ptr is a null pointer, no action occurs.Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.
Is it possible to call C or C++ code from a Java Code, i can re-write the code in Java, but need to reuse the existing code.. Thanks
Yes, it's possible using theJava Native Interface.
What is the portable way to check whethermallocfailed to allocate non-zero memory block?
According to theSingle Unix Specification,mallocwill returnNULLand seterrnowhen it fails.
``` int setsockopt( SOCKET s, int level, int optname, const char* optval, int optlen ); ``` SO_DEBUG Windows Sockets service providers are encouraged (but not required) to supply output debug information if the SO_DEBUG option is set by an application. The mechanism for generating the debug information and the form it takes are beyond the scope of this document. I did not find any scope.
It doesn't work on win32. Enables debug output. Microsoft providers currently do not output any debug information. I believe it was pulled with a lot of other stuff to maintain some compatibility with the BSD socket APIs.
Say I have a thread that's something like this: ``` void my_thread(char *device_name) { int fd = open(device_name, O_RDONLY); struct input_event ev; while(1) { read(fd, &ev, sizeof(struct input_event)); /* do something */ } } ``` How do I stop such a thread? One way is usingpthread_cancel, but I'd rather do it more gracefully. Something likepthread_killperhaps? In such case, however, would the read method unblock (as I presume it should) and how would the thread handle the signal? Or is it the process that should handle it? I'd be very grateful for an advice!
You problem is actually "how to interrupt blocking system call from other thread". Try searching for it. Here is one of the similar discussions:Proper way to close a blocking UDP socket
It seems to me that bothsignalandsocketcan be used for this job, how do you decide which one to use actually?
Using signals for IPC is sort of inconvenient and primitive. You should really be choosing between Unix sockets (not TCP ones!) and pipes. Pipes are generally easier to program with, since they guarantee that a singlewriteunder the size ofPIPE_BUFis atomic. They do have their limitations however. For example, when the writer is faster than the reader, the writer starts to block when the pipe buffer gets full. The size of this buffer by default is around 64k, and it cannot be changed without recompiling the kernel, at least in Linux. Pipes are also unidirectional, which means that you'll have to keep a pair of pipes in each process, one for reading and one for writing. Unix sockets have a configurable send buffer size and a more advanced programming interface.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed7 years ago.Improve this question I remember seeing once a jsfiddle type of thing (online compiler) where you can specify the language (c, c++, asm) and the input and output and it compiles it and displays the output from the website. Anyone know what I'm talking about?
There are many, two most popularly used here in SO are: Ideone.comcodepad.org And all you have to do to find more is use google. A simple search yields thousands ofresults. I usually stick the two I mentioned above because I have seen them working reliably.
I want to find out storage type of variables in a function block. How to check if compiler has elevated auto variable storage to register storage or if variables declared with register storage are honored by compiler? I am assuming by seeing the assembly code of the obj file after optimization would give us an idea. Please list the switch that I need to use with gcc or cl.exe to get this information?
The-Sswitch in gcc is the one you are looking for.See§3.2 Options Controlling the Kind of Output (GCC manual)
GNU Emacs is easily extended with Emacs Lisp. In some cases you may hit a performance wall even after byte compiling. In this situation it would be useful to be able to write C functions that you could call from Emacs Lisp code. Is this possible? How do you do it? Is there example code?
Isthis (Writing Emacs Primitives)what you are looking for?
What tools for Windows and Linux systems can I use to determine alignment issues, cache misses and other parameters relevant to code generated by Visual C++ and GCC? Can I use these tools to determine the alignment of structures so I can avoid compiler-generated padding?
To determine cache misses you'll want a CPU-level profiler, likeoprofileorvtune, or a dynamic instrumentation tool, likevalgrindwithcachegrind. To look for alignment issues on structures, there is a tool calledpaholefor object files withDWARFdebugging information.
I have some simple question, when I do something like that: ``` int* ptr1 int* ptr2 if(ptr1 == ptr2)... ``` What do I actually compare: ``` 1. addresses where ptr1 and ptr2 saved 2. addresses where content of pointers saved ``` If there is 1, how can I check 2?
That compares the pointer values, which are addresses. Soptr1==ptr2tests whether the two pointers point to the same address -- your #2. You could express #1 -- comparing the addresses of the pointers themselves -- with&ptr1 == &ptr2, but here you know that that will be false.
Is there is an equivalent in C or Objective-C to do the following (taken from Java) ``` Integer.toHexString(some_int) ```
For 32 bit Integers: ``` char buffer[enough_space_for_the_largest_string..]; sprintf (buffer, "%08x", YourNumber); ```
Is there a way to kill a zombie process? I've tried callingexitto kill the process and even sendingSIGINTsignal to the process, but it seems that nothing can kill it. I'm programming for Linux.
Zombie processes are already dead, so they cannot be killed, they can only be reaped, which has to be done by their parent process viawait*(). This is usually called thechild reaperidiom, in the signal handler forSIGCHLD: ``` while (wait*(... WNOHANG ...)) { ... } ```
I am new in Linux and system programming . I Want to write a c program which finds processes whose cpu% usage are more than a specific given value and sends them to background. anybody can help me ! I really appreciate it
I'm fairly sure that what you're asking is that you want to detect if a process is using X amount of CPU and if so, take it off the CPU for a while. There's a piece of software already that does this: It's called the kernel. I'm not aware of any way to programatically take another process off CPU unless that other program supports an external interface to reduce its load. Most likely what you really want to do is configure theniceand other scheduler parameters of the running process so the kernel is more like to to take it off CPU when another program needs to do work. But what underlying problem are youreallytrying to solve here? Maybe if you tell us that we can offer an alternate solution.
How can the following C function be wrapped with SWIG? ``` int add_option(const unsigned char *data); ``` Currently I get this wrapped to: ``` public static int add_option(SWIGTYPE_p_unsigned_char data); ``` Is it possible to wrap it for String, Byte[] or something similar?
``` %module Example %{ int func(const unsigned char *data); %} %include <arrays_java.i> %apply signed char[] { const unsigned char *data}; int func(const unsigned char *data); ``` Use this code !!!!!
this type of declaration of function is valid inCbut why not inC++? ``` int sum(i,j)int i,j; { return i+j; } ```
This is because that old-style function definition declares no prototype. That is, the caller would not know what parameter types the function expects. In C++, that's too much of a type safety miss. In particular, the FDIS says Change:In C++, the syntax for function definition excludes the "old-style" C function. In C, "old-style" syntax is allowed, but deprecated as "obsolescent."Rationale:Prototypes are essential to type safety.Effect on original feature:Deletion of semantically well-defined feature.Difficulty of converting:Syntactic transformation.How widely used:Common in old programs, but already known to be obsolescent.
I'm trying to figure out how to call a c function from an obj-c file. I've seen some good examples of how to do the opposite. In the example below I have an objective c file. It contains a c function named setup. I want to be able to create an instance of my obj-c file in the regular way and then call the setup function. Header ``` #import <Foundation/Foundation.h> void setup(int,float); @interface Test : NSObject { } @end ``` Source ``` #import "Test.h" #include <stdio.h> #include <stdlib.h> void setup(int val1,float val2) { //do something with values } @implementation Test @end ``` View did load ``` Test *test =[Test alloc]init] //this does not work test.setup(6,1.4); ```
Just call setup(). As declared, is in no way tied to an object - it's just a regular C function.
Is there a clean way to limit the number of hits from an SQLite3SELECTstatement? For example, I might query withSELECT * FROM myTable WHERE name='Smith';realising I could encounter thousands of hits. I'd like SQLite3 to give me say the first 10 it encounters and then terminate the query. How do I do this? If SQLite3 does not provide this immediately, is there anything I can edit in the SQLite3 source code from which I can rebuild? Assume I'm in an environment where I have only one thread and I'd like control back in a reasonable time.
You're looking for theLIMITclause: ``` SELECT * FROM myTable WHERE name='Smith' LIMIT 10 ```
I defined the following function, where List is a structure. ``` List * LIST_Create() { List * l = calloc(0, sizeof(List)); unsigned char * pc = (unsigned char *)l; for(i = 0; i < sizeof(List); i++) { LOG("LIST","0x%1x ", (unsigned char)*pc); pc++; } } ``` When I print out the bytes I get this: ``` LIST: 0xffffffbf LIST: 0x1 LIST: 0x13 LIST: 0x0 LIST: 0x1 LIST: 0x1 LIST: 0x0 LIST: 0x0 LIST: 0x0 LIST: 0x0 LIST: 0x0 LIST: 0x5 ``` what's going on? I know it isn't the printing that's the issue, because the code is reading non-zero values too. The only way I can reliably zero out the List structure seems to be to initialise all the members individually. I don't mind, but shouldn'tcalloc()work?
You allocated space enough for0Lists: ``` List * l = calloc(0, sizeof(List)); ``` Therefore your allocated memory is0bytes long.
gcc 4.6.0 GNU Emacs 23.2.1 I have some c code and at some point I must have made a typing mistake. And now I am left with unbalanced curly braches or a parentheses. I have about 2000 lines of code and I am just wondering is there any technique for finding them? Emacs has some good features, so I am just wondering is there any way it can scan the code and tell me where they are. Currently I have a compile error related to this. Many thanks for any suggestions,
In emacs you can useM-x check-parens. Seehttp://www.gnu.org/software/libtool/manual/emacs/Parentheses.html
Consider the following code: ``` char *myContent = "content"; int size = snprintf(NULL, 0, "INSERT INTO myTable (col1) VALUES('%s')",myContent); char *query = malloc(size+2); snprintf(query, size, "INSERT INTO myTable (col1) VALUES('%s')",myContent); ``` Now I have the problem that the last bracket is truncated: ``` (gdb) print query $2 = 0x616080 "INSERT INTO myTable (col1) VALUES('content'" ``` This is not a valid SQL statement, so have you an idea what the reason could be that the last bracket is missing?
snprintfreturns: the number of characters printed (not includingthe trailing '\0' used to end output to strings) But the size argument is: and vsnprintf() write at most size bytes (includingthe trailing null byte ('\0')) So you should: ``` char *query = malloc(size+1); snprintf(query, size+1, "INSERT INTO myTable (col1) VALUES('%s')",myContent); ```
How can i do inline C pure Assembly language? I wanted to do for loop but does not works. ``` #include <stdio.h> int main() { asm { for(int i=0; i<10; i++) { // is this how i will do the assembly language as inline C? // is this how the for loop looks as inline c? } } // ? } ```
Something similar to, ``` __asm{ xor esi,esi go: inc esi cmp esi,10 jnz go } ```
I'm not sure what this inline assembly does: ``` asm ("mov %%esp, %0" : "=g" (esp)); ``` especially the: "=g" (esp)part.
"=g" (esp)defines an output for the inline assembly. Thegtells the compiler that it can use any general register, or memory, to store the result. The(esp)means that the result will be stored in the c variable namedesp.mov %%esp, %0is the assembly command, which simply moves the stack pointer into the 0th operand (the output). Therefore, this assembly simply stores the stack pointer in the variable namedesp.
I wrote following program ``` #include<stdio.h> main () { extern int i; printf("\n%d",i); } int i=30; ``` I was expecting an error message as i is initialized after main but on the contrary the program gave me output.Why it did not gave me an error is what I want to know.
The entire purpose ofexternis that it says "there is a variable of typeintcalledi, somewhere in the project, that may be linked in later. just assume it exists". You could defineiin an entirely separate.cfile and it'd still work as long as you linked the.ofiles together.That's whatexterndoes. It's just like how you can declare a function and use it, even if it's defined in a completely separate.cfile (or, indeed, later on in the same one). Read the chapter in your C book aboutextern.
There are many example thread based web servers online, but I haven't really seen anything that gives a good example of an event-loop based one (without being very complex, e.g. lighttp and nginx). Are there any? If not, what should I read/look at to help me learn how to make a server of this sort? (This includes asynchronous IO in C, etc.) I already understand the basics of how event-loop based programming works, especially in higher level languages like Python, but I need to be able to implement one in C.
Here is onewhich is part ofTupleServersource that useslibevent.
This question already has answers here:Closed12 years ago. Possible Duplicate:Struct initialization of the C/C++ programming language? I'm re-learning C and asking myself if something like this is possible: ``` typedef struct Link { struct Node a; struct Node b; float weight; } Link; Link links[LINK_NUMBER]; links[0] = {nodes[0], nodes[1], 5}; ``` instead of: ``` Link link0 = {nodes[0], nodes[1], 5}; links[0] = link; ```
that's what I was searching for: ``` links[0] = (Link) {nodes[0], nodes[1], 5}; ```
Say I have 1 million structs, each containing integers, doubles, strings, and other structs, something like: ``` struct s1 { int f1; long f2; char* f3; }; struct s2 { struct s1* f1; double f2; }; ``` How can I save these to a file in binary format, then look up and load them from that file, on platforms different from the one the executable was compiled on, without worrying about endianness, float representation and other platform-specific gotchas? The reason for preferring a binary format is mainly size of the resulting file. If integers alone look like "32435" and I have millions of them, the extra 3 bytes per integer would add quite a bit of size to the file.
Write them as ascii text, XML or some similar non-binary format.