question
stringlengths
25
894
answer
stringlengths
4
863
For instance if I called WriteFile to the end of a file, and later I wanted to delete the written bytes, how could I do this? Do I have to read the file's contents into a buffer, re-create the file, and write the desired bytes, or is there an easier way?
Seekto the file position you want to truncate from (if you're not already there), then call the aptly-namedSetEndOfFile()function.
How can I understand the parsing of expressions like ``` a = b+++++b---c--; ``` in C? I just made up the expression above, and yes, I can check the results using any compiler, but what I want to know is theground rulethat I should know to understand the parsing of such expressions in C.
From the standard 6.2(4): If the input stream has been parsed into preprocessing tokens up to a given character, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token. They even add the example: EXAMPLE 2 The program fragment x+++++y is parsed as x ++ +...
I'm trying to encode and transfer raw video frames over LAN (100 Mbps) connection (frames captured by a web cam). What video/image encoding format is recommended for fast compression (with not much regard for the compression ratio) ? Thanks,
If you need individual frames to be independent of one another, use mjpeg (which is equivalent to encoding each frame as a jpeg). It's simple and you have plenty of tools with which to manipulate it. Otherwise, as long as you have a remotely modern cpu and the resolution isn't insanely high, just use a simple mpeg4 a...
Is there a way to set the blending parameters so the whole scene renders in grayscale? (without using GLSL, only pipeline functions) Thanks
No, all colors are separated. You need a pixel shader for that
We're using Redis for monitoring on a high traffic web application. The app is written in c and uses the credis client library. We're seeing enormous numbers of TIME_WAIT connections left over from our communications with Redis: $ netstat -a | grep 6379 | grep TIME_WAIT | wc -l 15865 Any idea what's going on here?...
SeeSO question #337115for approaches to this problem. (I prefer making the client close the connection so the client ends up in the TIME_WAIT state.)
I have aC-program(an Apache module, i.e. the program runs often), which is going towrite()a 0-terminated string over a socket, so I need to know its length. The string is #defined as: ``` #define POLICY "<?xml version=\"1.0\"?>\n" \ "<!DOCTYPE cross-domain-policy SYSTEM\n" \ "\"http://www.adobe.com/xml/dtds/cr...
Usesizeof(). e.g.sizeof("blah")will evaluate to5at compile-time (5, not 4, because the string literal always includes an implicit null-termination character).
I have some vars live: ``` int foo1; int foo2; .. ``` and I want to reach them from: ``` for (int i = 1;i<=2;i++) { // howto get foo1 and foo2? } ``` how to get them? EDIT, end what when it will be no int but a Opject *pointer;?
You can't; you need an array of some kind. e.g.: ``` int foo[2]; /* Two elements, foo[0] and foo[1] */ for (int i = 0; i < 2; i++) { foo[i] = i; } ``` or: ``` int foo1; int foo2; int *p[] = { &foo1, &foo2 }; /* Array of pointers */ for (int i = 0; i < 2; i++) { *p[i] = i; /* Changes foo1 or foo2 */ }...
I have a process that continuously needs to write information. Furthermore, there is a second process which sometimes connects to the "information channel" of the writing process and should read the information that are written since it's connected. This process might also deconnect and reconnect several times again. ...
You could use Unix-domain sockets, or regular TCP sockets on loopback interface.
I need to use natural cubic spline interpolation in an iPhone app. Does anyone know of a class for Obj C or C that resembles this:http://www.ee.ucl.ac.uk/~mflanaga/java/CubicSpline.html "performing an interpolation within a one dimensional array of data points, y = f(x), using a cubic spline."
Look at thisarticleThis is a sample for Curve Fitting. It uses Cubic Spline Interpolation, and Bezier Spline Curve.
``` #include<stdio.h> int main(void) { char c = 0x80; printf("%d\n", c << 1); return 0; } ``` The output is-256in this case. If I writec << 0then the output is-128. I don't understand the logic behind this code.
charmay be signed on your platform, in which case0x80represents -128 (assuming two's complement). When acharis used as an operand with the<<operator, it is promoted toint(still -128). So when you apply the left-shift, you get -256. Technically, shifting negative values isimplementation-definedundefined, but what yo...
I have a C source file having comments in//(C++) style. I want to change all the comments to the old/* */(C) style. Is there a way to do this using an existing script?
A substitution with you favorite editor and a regular expression likes#//(.*)#/*\1 */#should do it...
How do I cause a thread to respond topthread_cancel()if it is blocked on asem_wait()?
You can set a signal handler, let's says for SIGUSR1, for the thread that will be blocking then, from another thread, you callpthread_cancel(tid)andpthread_kill(tid, SIGUSR1). The thread will be canceled oncesem_wait()is interrupted by the signal.
Many times I see in open source code that a call to a C function is cast to void. For example, in the source code forls(http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/cmd/ls/ls.c) I see the following. ``` (void) setlocale(LC_ALL, ""); ``` Why is this good practice?
It explicitly means you ignore the return value, and did not just forget it.
I am looking for a automated finite state machine generator for C? I have seen a few over the internet but unable to decide which one to use. If anybody worked with any such tool then help me to find the right one. Thanks, Ravi Gupta
Ragelis fairly powerful.
I know that C strings are char[] with a '\0' in the last element. But how are the chars encoded? Update: I found this cool link which talks about many other programming languages and their encoding conventions:Link
All the standard says on the matter is that you get at least the 52 upper- and lower-case latin alphabet characters, the digits 0 to 9, the symbols! " # % & ' ( ) * + , - . / : ; < = > ? [ \ ] ^ _ { | } ~, and the space character, and control characters representing horizontal tab, vertical tab, form feed, alert, back...
I would like to model an event-driven finite state machine in C as proposed here :http://en.wikipedia.org/wiki/Event-driven_finite_state_machine But I would also like the 'external' events to be handled in various threads. Can I find such a code somewhere ? Or advices ?
Message queues are a way to solve your problem. If you want to feed your state machine with external events from other threads, they can write these events in a message queue that will be read by your state machine. If you want that other threads trigger on actions from your state machine, it can write to various me...
I am taking a file path from a user. I need to then access that file, and create it if it does not exist. I also need to create any intermediate directories if they don't exist as well. For example, if my directory looks like: ``` mydir | +---subdir | | | +-- FileA | +---File1 ``` I might receive mydir/subdir/F...
I think this answer covers your question: Recursive mkdir() system call on Unix In short, you must create the subdirs yourself.
So... I will have a project which will be tested on Win 7 and some Linux server. It will be a web service that will use HSQLDB, Hibernate, Spring, Blaze DS and Flash (Flex RIA) as front end. I need to implement into it some image filtering\editing functionality which will be implemented in cross-platform C++ code (It...
It sounds like you'll benefit from the Java Native Interface. If you've got existing C and C++ code that you'd like to use from Java you may want to seriously consider something likeGlueGen. It will save you a lot of time generating the code to access your C code. You can have a look at the official Java JNI Examples...
I'm Interested in writing gedit-plugins in C. I've checkedGedit/NewMDIPluginHowTo...but haven't had any luck with it. How can I get more information about writing gedit plugins in C?
If you're willing to use Python instead,hereis a tutorial for writing gedit plugins in Python.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
Project Euleris pretty good. They have some simple challenges that may be suitable. These won't really do much to teach them C, though. Text books are much better for that. Additionally, you could have them write a program to balance chemical reaction equations. That would be good for I/O and simple math.
I have astaticvariable in source filetest_1.cdeclared as: ``` static char var1 = 0; ``` I need to access the current value of this variable from source filetest_2.c. So, I did something like: In test_1.c ``` static char var1 = 0; volatile char var_another = var1; ``` and intest_2.c, I declare the variablevar_anot...
staticandexternare mutually exclusive. If you want to access yourstatic char var1from a different file, you'll have to remove thestaticand just make it a regular global. You don't needvolatileat all. Alternatively, you can make an accessor function that returns the value ofstatic char var1and use that from your other...
I have#include<math.h>, and I tried to use pow(x, y) and powf(x, y). but it seems neither of them are under c99 standard. and I use the commandgcc -std=c99 test.c -o testto compile. what function there exists I can use?
Forhistericalreasons, the math library is not bundled in with the rest of the Standard Library. You have to manually add it to the compilation with the-lmoption to gcc. ``` gcc -std=c99 test.c -o test -lm ```
My c/c++ skills are non-existent and there's some custom string array data that needs to be returned from an old C dll fyi - The C/C++ code can be modified as needed
Without more information about your specific case, it's impossible to say how you'd marshal the return value. Perhaps this page of interop marshaling samples will help:http://msdn.microsoft.com/en-us/library/e765dyyy.aspx The above link no longer works. TryMarshaling Data with Platform Invoke.
I am looking for a automated finite state machine generator for C? I have seen a few over the internet but unable to decide which one to use. If anybody worked with any such tool then help me to find the right one. Thanks, Ravi Gupta
Ragelis fairly powerful.
I know that C strings are char[] with a '\0' in the last element. But how are the chars encoded? Update: I found this cool link which talks about many other programming languages and their encoding conventions:Link
All the standard says on the matter is that you get at least the 52 upper- and lower-case latin alphabet characters, the digits 0 to 9, the symbols! " # % & ' ( ) * + , - . / : ; < = > ? [ \ ] ^ _ { | } ~, and the space character, and control characters representing horizontal tab, vertical tab, form feed, alert, back...
I would like to model an event-driven finite state machine in C as proposed here :http://en.wikipedia.org/wiki/Event-driven_finite_state_machine But I would also like the 'external' events to be handled in various threads. Can I find such a code somewhere ? Or advices ?
Message queues are a way to solve your problem. If you want to feed your state machine with external events from other threads, they can write these events in a message queue that will be read by your state machine. If you want that other threads trigger on actions from your state machine, it can write to various me...
I am taking a file path from a user. I need to then access that file, and create it if it does not exist. I also need to create any intermediate directories if they don't exist as well. For example, if my directory looks like: ``` mydir | +---subdir | | | +-- FileA | +---File1 ``` I might receive mydir/subdir/F...
I think this answer covers your question: Recursive mkdir() system call on Unix In short, you must create the subdirs yourself.
So... I will have a project which will be tested on Win 7 and some Linux server. It will be a web service that will use HSQLDB, Hibernate, Spring, Blaze DS and Flash (Flex RIA) as front end. I need to implement into it some image filtering\editing functionality which will be implemented in cross-platform C++ code (It...
It sounds like you'll benefit from the Java Native Interface. If you've got existing C and C++ code that you'd like to use from Java you may want to seriously consider something likeGlueGen. It will save you a lot of time generating the code to access your C code. You can have a look at the official Java JNI Examples...
I'm Interested in writing gedit-plugins in C. I've checkedGedit/NewMDIPluginHowTo...but haven't had any luck with it. How can I get more information about writing gedit plugins in C?
If you're willing to use Python instead,hereis a tutorial for writing gedit plugins in Python.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
Project Euleris pretty good. They have some simple challenges that may be suitable. These won't really do much to teach them C, though. Text books are much better for that. Additionally, you could have them write a program to balance chemical reaction equations. That would be good for I/O and simple math.
I have astaticvariable in source filetest_1.cdeclared as: ``` static char var1 = 0; ``` I need to access the current value of this variable from source filetest_2.c. So, I did something like: In test_1.c ``` static char var1 = 0; volatile char var_another = var1; ``` and intest_2.c, I declare the variablevar_anot...
staticandexternare mutually exclusive. If you want to access yourstatic char var1from a different file, you'll have to remove thestaticand just make it a regular global. You don't needvolatileat all. Alternatively, you can make an accessor function that returns the value ofstatic char var1and use that from your other...
I have#include<math.h>, and I tried to use pow(x, y) and powf(x, y). but it seems neither of them are under c99 standard. and I use the commandgcc -std=c99 test.c -o testto compile. what function there exists I can use?
Forhistericalreasons, the math library is not bundled in with the rest of the Standard Library. You have to manually add it to the compilation with the-lmoption to gcc. ``` gcc -std=c99 test.c -o test -lm ```
My c/c++ skills are non-existent and there's some custom string array data that needs to be returned from an old C dll fyi - The C/C++ code can be modified as needed
Without more information about your specific case, it's impossible to say how you'd marshal the return value. Perhaps this page of interop marshaling samples will help:http://msdn.microsoft.com/en-us/library/e765dyyy.aspx The above link no longer works. TryMarshaling Data with Platform Invoke.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
use vim with plugins like snipMate, c-support etc.
I've downloaded Eclipse C/C++ IDE . I need to run a simple c program in this(To print welcome). While trying to run the program its popping up an error message like"Launch failed: Binary not found" . Need i install any compiler package. ? Please help me to do this.
Yes, you have to install a compiler, Eclipse is only an IDE. You can get MinGWhere.
This question already has answers here:Closed12 years ago. Possible Duplicate:What does a colon in a struct declaration mean, such as :1, :7, :16, or :32? This is C code sample of a reference page. ``` signed int _exponent:8; ``` What's the meaning of the colon before '8' and '8' itself?
It's a bitfield. It's only valid in astructdefinition, and it means that the system will only use 8 bits for your integer.
Just more a general question I can't seem to find a definite answer on. But what is a good SQL wrapper for C++ that allows me to call queries? I'm used to Oracle, but i've used MYSQL before aswell. And how would you call something such as an insert statement (for example) in one?
Personally I loveSOCI, simple and easy to use, just follow the link for easy example code and a much better explanation of what SOCI is all about then I could put in this answer. I use this for all of my C++ SQL development work.
I recently read a sample job interview question: Write a function to convert an integer to a string. Assume you do not have access to library functions i.e., itoa(), etc... How would you go about this?
fast stab at it: (edited to handle negative numbers) ``` int n = INT_MIN; char buffer[50]; int i = 0; bool isNeg = n<0; unsigned int n1 = isNeg ? -n : n; while(n1!=0) { buffer[i++] = n1%10+'0'; n1=n1/10; } if(isNeg) buffer[i++] = '-'; buffer[i] = '\0'; for(int t = 0; t < i/2; t++) { buffer[t] ^=...
Is there an easy way to check if a line is empty. So i want to check if it contains any white space such as \r\n\t and spaces. Thanks
You can use theisspacefunction in a loop to check if all characters are whitespace: ``` int is_empty(const char *s) { while (*s != '\0') { if (!isspace((unsigned char)*s)) return 0; s++; } return 1; } ``` This function will return 0 if any character is not whitespace (i.e. line is not empty), or ...
I have a value thats 5 bits in length. 4 bits determine the number and the 5th bit determines the sign, there by holding any value between -16 and +15. How can I accomplish sign extending from a constant bit width in C#? I know in C, I can use something like the follow to accomplish this: ``` int x; // convert this f...
It's not really clear what you mean, but itcouldbe as simple as: ``` int fiveBits = normal & 0x1f; ``` and for the reverse: ``` int normal = fiveBits < 16 ? fiveBits : fiveBits | -32; ``` If you could suggest some original input and desired output, that would help.
I am trying to observe if software can damage hardware today or not.For that I choose that choosing to shut the computer fans would be a nice idea(else I would have preferred crashing the harddisk).I need to know the following: Is it possible to do that anyone's computer?Can this be dangerous to the hardware?Choosin...
First of all, the fans spin for a reason: complex electronics overheat rather quickly. It would be easier to look into a specialized tool that does this, such as SpeedFan for Windows. On the other hand, if youreallywant to do it, there are ways - however, they are mostly vendor- and product-specific. For Acer laptops...
For regular expression \w+\d, in many script language such as perl/python it can be written literally. But in C/C++, I must write it as: ``` const char *re_str = "\\w+\\d"; ``` which is ugly to eye. Is there any method to avoid it? MACRO are also acceptable.
Just as an FYI, the next C++ standard (C++ 0x) will have something calledraw string literalswhich should let you do something like: ``` const char *re_str = R"(\w+\d)"; ``` However until then I think you're stuck with the pain of doubling up your backslashes if you want the regex to be a literal in the source file.
printfconversion specifications are%followed by flags, width, precision, length modifier and conversion specifier. Is there practical limit to size of a conversion specification? I.e.%sis 2 chars long, while%08.2fis 6 chars long. My question is, what is the length of the maximal single specification in a format strin...
There is no such conversion specification of maximum length. If you think you've found such a spec, I can come up with one that is one char longer. For example, consider field width and precision. The standard says they are decimal integers but does not specify their range. Therefore you can write conversion specifie...
``` # include <stdio.h> int x = 5; int main(void) { int x = 7; printf("output = %d\n", x); } ``` The above program shows output as7. How to print5inc? thanx...
So you're asking how to access a global that's shadowed by a local? You can't in that scope, but something like this should work ``` # include <stdio.h> int x = 5; int get_global_x() { return x; } int main(void) { int x = 7; printf("output = %d\n", get_global_x()); } ```
My input data is 16-bit data, and I need to find a median of 3 values using SSE2 instruction set. If I have 3 16-bits input values A, B and C, I thought to do it like this: ``` D = max( max( A, B ), C ) E = min( min( A, B ), C ) median = A + B + C - D - E ``` C functions I am planing to use are : max - _mm_max_epi...
Your idea is quite clever but you can do it with fewer operations just using max and min. ``` t1 = min(A, B) t2 = max(A, B) t3 = min(t2, C) median = max(t1, t3) ``` This will be just 4 SSE instructions compared with 8 in your original implementation. Note that this is actually just a prunedsorting networkfor N = 3....
I want to read in a string and parse it with sscanf. Although i don't want to read in any spaces in the beginning. Sample string. ``` @a Bear Tiger sscanf(strLine, "@%1s %64s %64s", dir, name1, name2); ``` I have that. Problem is if the line goes in as say ``` @a Bear Tiger ``` Should be: ``` @a Bear Tiger ```...
``` sscanf(strLine, " @%1s %64s %64s", dir, name1, name2); ``` This is necessary becausescanfonly skips whitespace for (most) conversion specifications. But@is an "ordinary character", not a conversion specification, so there is no skip. However, adding whitespace to the format string forces input whitespace to be ...
I was trying to develop a chat application using C programmable sockets. I need to check whether the stdin buffer has some value in it to send the message to the client/server and receive it. But I don't know how to check the stdin buffer for values. Please help.
You wantselect(2,3p).
Is there a way to find out if a socket is already in Non-Blocking mode in Windows? I know this can be done in case of Linux, but, I am unable to find any way for this Windows. All my coding is in 'C' language. Is there a way?
The only way you can check this is by doing something illegal on a nonblocking socket and checking that it fails in an expected way. Hardly the most robust design. The socket will be blocking unless you explicitly set it nonblocking usingWSAIoctlorioctlsocketwithFIONBIO. That cannot be too hard to check in your code...
Many times I need to do things TWICE in a for loop. Simply I can set up a for loop with an iterator and go through it twice: ``` for (i = 0; i < 2; i++) { // Do stuff } ``` Now I am interested in doing this as SIMPLY as I can, perhaps without an initializer or iterator? Are there any other, really simple and elegan...
This is elegant because it looks like a triangle; and triangles are elegant. ``` i = 0; here: dostuff(); i++; if ( i == 1 ) goto here; ```
``` struct stats { char top : 1; char bottom : 1; char side : 2; } MyStat; ``` I have seen this format with integers but how does the above char bit field work and what does it represent? Thank You.
Char bit fields work in the same way as int, just the base type is 8-bit wide, not 32-bit. So you'd get a struct stats, which has the size of 1 byte, and 3 member variables, occupying a total of 4 bits.
I'm trying to compile the following code using the MPLAB C18 v3.36 compiler. Compiler returns a syntax error on 'char rij;'. But when i put char rij; a line earlier (before TRISA = ...), it compiles ... ``` void setup(void) { TRISD = 0b00000000; TRISA = 0b00000000; char rij; for (rij = 0; rij<ROWS; rij++) { r...
Although I'm not familiar with this compiler I would guess that it follows C89 semantics which forbid mixing declarations with statements. Therefore you can only declare variables on the beginning of the block.
``` void clearscreen ( void ) { char a = 'a' ; fflush ( stdout ); do{ a = getc( stdin ) ; if ( isspace ( (int ) a ) ) { getc ( stdin ); } }while ( a != EOF ); ...
If you're working with a ANSI-compliant terminal (which is probably the case if you're under Linux), then you can useescape sequences.
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. ``` char* fun(char *s) { char buf...
Two problems: You are returning a pointer to the character array that islocalto the function.Inprintf("%c",p);it should be*p
This question already has answers here:Closed12 years ago. Possible Duplicate:C : How do you simulate an 'exception' ? Hi, I know that exception handling is available in C++ but not in C. But I also read that exception handling is provided from OS side, so isnt there any function for C invoking the same behavior fro...
The C language itself has no support for exception handling. However a means of exception handling for C does exist on a platform + compiler specific basis. In windows for example C programs can use SEH exception handling. http://www.microsoft.com/msj/0197/Exception/Exception.aspx I've seen arguments in the past t...
I'm wondering if my implementation should expect that reentrant mutex's are supported or not. The code is supposed to portable/platform independent. I'm wondering if mutex recursion is common enough that it shouldn't be a concern.
It's usually a distinct option, available through a different function call. Even then it isn't "detected" it's just "permitted". Sometimes, you WANT the lock to be recursive. Sometimes, you DON'T want the lock to be recursive. Any solution you come up with without explicitly allowing both conditions will not work un...
I would like to parse a html page and extract the meaningful text from it. Anyone knows some good algorithms to do this? I develop my applications on Rails, but I think ruby is a bit slow in this, so I think if exists some good library in c for this it would be appropriate. Thanks!! PD: Please do not recommend anyt...
UseNokogiri, which is fast and written in C, for Ruby. (Using regexp to parse recursive expressions like HTML isnotoriously difficult and error proneand I would not go down that path. I only mention this in the answer as this issue seems to crop up again and again.) With a real parser like for instance Nokogiri ment...
With reference to the semaphore implementation of semaphore.h in Linux, does an uninitialized semaphore sem_t default to 0? I just discovered that I had forgotten to initialize my semaphores to 0. Even so, the program worked fine without sem_init. (To all the purists, I completely agree that doing so is a bad practi...
It will depend on how/where the semaphore is defined. If it is defined as (part of) a global variable, then the compiler must initialise it to 0 if you don't specify any valueThis is also true when it is (part of) a block-scope variable declared asstatic.If it is (part of) a non-staticblock-scope variable, then it wi...
Is there a way to find out if a socket is already in Non-Blocking mode in Windows? I know this can be done in case of Linux, but, I am unable to find any way for this Windows. All my coding is in 'C' language. Is there a way?
The only way you can check this is by doing something illegal on a nonblocking socket and checking that it fails in an expected way. Hardly the most robust design. The socket will be blocking unless you explicitly set it nonblocking usingWSAIoctlorioctlsocketwithFIONBIO. That cannot be too hard to check in your code...
Many times I need to do things TWICE in a for loop. Simply I can set up a for loop with an iterator and go through it twice: ``` for (i = 0; i < 2; i++) { // Do stuff } ``` Now I am interested in doing this as SIMPLY as I can, perhaps without an initializer or iterator? Are there any other, really simple and elegan...
This is elegant because it looks like a triangle; and triangles are elegant. ``` i = 0; here: dostuff(); i++; if ( i == 1 ) goto here; ```
``` struct stats { char top : 1; char bottom : 1; char side : 2; } MyStat; ``` I have seen this format with integers but how does the above char bit field work and what does it represent? Thank You.
Char bit fields work in the same way as int, just the base type is 8-bit wide, not 32-bit. So you'd get a struct stats, which has the size of 1 byte, and 3 member variables, occupying a total of 4 bits.
I'm trying to compile the following code using the MPLAB C18 v3.36 compiler. Compiler returns a syntax error on 'char rij;'. But when i put char rij; a line earlier (before TRISA = ...), it compiles ... ``` void setup(void) { TRISD = 0b00000000; TRISA = 0b00000000; char rij; for (rij = 0; rij<ROWS; rij++) { r...
Although I'm not familiar with this compiler I would guess that it follows C89 semantics which forbid mixing declarations with statements. Therefore you can only declare variables on the beginning of the block.
``` void clearscreen ( void ) { char a = 'a' ; fflush ( stdout ); do{ a = getc( stdin ) ; if ( isspace ( (int ) a ) ) { getc ( stdin ); } }while ( a != EOF ); ...
If you're working with a ANSI-compliant terminal (which is probably the case if you're under Linux), then you can useescape sequences.
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. ``` char* fun(char *s) { char buf...
Two problems: You are returning a pointer to the character array that islocalto the function.Inprintf("%c",p);it should be*p
This question already has answers here:Closed12 years ago. Possible Duplicate:C : How do you simulate an 'exception' ? Hi, I know that exception handling is available in C++ but not in C. But I also read that exception handling is provided from OS side, so isnt there any function for C invoking the same behavior fro...
The C language itself has no support for exception handling. However a means of exception handling for C does exist on a platform + compiler specific basis. In windows for example C programs can use SEH exception handling. http://www.microsoft.com/msj/0197/Exception/Exception.aspx I've seen arguments in the past t...
I'm wondering if my implementation should expect that reentrant mutex's are supported or not. The code is supposed to portable/platform independent. I'm wondering if mutex recursion is common enough that it shouldn't be a concern.
It's usually a distinct option, available through a different function call. Even then it isn't "detected" it's just "permitted". Sometimes, you WANT the lock to be recursive. Sometimes, you DON'T want the lock to be recursive. Any solution you come up with without explicitly allowing both conditions will not work un...
I would like to parse a html page and extract the meaningful text from it. Anyone knows some good algorithms to do this? I develop my applications on Rails, but I think ruby is a bit slow in this, so I think if exists some good library in c for this it would be appropriate. Thanks!! PD: Please do not recommend anyt...
UseNokogiri, which is fast and written in C, for Ruby. (Using regexp to parse recursive expressions like HTML isnotoriously difficult and error proneand I would not go down that path. I only mention this in the answer as this issue seems to crop up again and again.) With a real parser like for instance Nokogiri ment...
With reference to the semaphore implementation of semaphore.h in Linux, does an uninitialized semaphore sem_t default to 0? I just discovered that I had forgotten to initialize my semaphores to 0. Even so, the program worked fine without sem_init. (To all the purists, I completely agree that doing so is a bad practi...
It will depend on how/where the semaphore is defined. If it is defined as (part of) a global variable, then the compiler must initialise it to 0 if you don't specify any valueThis is also true when it is (part of) a block-scope variable declared asstatic.If it is (part of) a non-staticblock-scope variable, then it wi...
i want to write a program using multi-threading, raw sockets, to scan the ports in python i have a C code for injection of raw socket. i want to perform a ACK scan so need a raw socket. So please help me. thank you
Please check outCython. It makes it very easy to wrap C code. This is adapted from thedocumentation on calling external C functions: ``` cdef extern from "math.h": double sin(double) def pysin(x): return sin(x) ``` You could then callpysinfrom the compiled module like a normal Python module.
Is there a way to put a breakpoint on any function in Visual Studio, sort of likebm kernel32!LoadLib*in WinDbg? I know one way is to break at application start, find the required DLL load address, then add offset to required function you can get via Depends, and create a breakpoint on address. But that's really slow,...
Go to "Debug / New breakpoint / Break at function..." and paste the function name. For APIs, this can be tricky, as the name of the function as seen by the debugger is different from its real name.Examples: ``` {,,kernel32.dll}_CreateProcessW@40 {,,user32.dll}_NtUserLockWindowUpdate@4 ``` See this blog post to find...
If the following pieces of code execute in the order in which I have put them, can I be sure that thread 1 is awoken first by thread 3, later followed by thread 2? ``` main: sem_init(&x,0,0); thread 1: sem_wait(&x); thread 2: sem_wait(&x); thread 3: sem_post(&x); ```
There is no reason to make such an assumption. It depends on when thread 1 and thread 2 are invoquing sem_wait(), i.e., on what they do before and how the scheduler gives them CPU for running. If you want that thread 1 be awoken before thread 2, you need another semaphore: ``` main: sem_init(&x,0,0); sem_init(&y,0,0)...
I have executed a process using CreateProcess, but I want to fetch or dump the memory area allocated to the process, preferably in real time. Unfortunately I do not know how to recieve the pointer to the memory are after creating the process. I've been searching around, but I have not found any useful answers so far. ...
TryVirtualQueryEx()to see what memory pages are used, andReadProcessMemory()to read them.
In the following code, I get a warning that there is an implicit declaration of function getpgid. I know its only a warning, but its for a class and the professor wants us to treat warnings as errors. So, help please. I have included the appropriate header file as well so I have no idea whats wrong: ``` #include <un...
From theman page: Feature Test Macro Requirements for glibc (seefeature_test_macros(7)):getpgid(): _XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED || /* Since glibc 2.12: */ _POSIX_C_SOURCE >= 200809L
I have a simple C/CPP process running on a linux system. This is a.out. Another process is capable to start a.out inside its code. This is b.out. What code do I need inside a.out to understand that it is executed from the command line? Eg ./a.out Is there a way a process to know if it started from the cmd or starte...
You can't find out in general whether a program was started "from the command line" (by a user's explicit command), but you can find out whether its standard input and output are talking to a terminal/command window: ``` #include <unistd.h> isatty(fileno(stdin)) ``` andstdoutreturn whether standard input/standard ou...
I would like to enable tabbing for my application. And so far it seems I could use a tab control. The problem with it is, though, that it creates a border around the client area. What I want, is more like a FireFox tab control, that only takes up a row in the application and doesn't create any frames around client are...
I'm pretty sure the tab control consists of two parts - the tab headers and the tab page. So you should be able to use the tab header only. It will take more work, but I think you can get what you want. Look at CTabCtrl and CHeaderCtrl - will those do it? I've never customized them, but it seems possible.
I have multiple threads, and I want each thread to wait for every others to complete at certain point in the code before proceeding as following: ``` void *run() { for (i=0;i<1000;i++){ do_1st(); // sync() all stop here wait for all then resume do_2nd(); } } ``` I tried to use pthread_cond_wait.. bu...
You can use apthread_barrier, initialize it before you start your threads, and set thecountto the no. of threads that's running your loop. e.g. if you have 8 threads: ``` pthread_barrier_init(&my_barrier,NULL,8); ``` The thread loop now becomes ``` void *run() { for (i=0;i<1000;i++){ do_1st(); pthread_ba...
there is someone that know if exist a XSD code generator for C source code? I have a lot of xsd files and I need to generate C struct and relative function fromXml and toXml. Thanks.
For C++ generation there ishttp://sourceforge.net/projects/xxsd2code/
This post is edited and the original post here is asking the implementation of _malloc_r which is not a good move to use. My question now is there any other malloc implementation or alternative function for malloc and free functions? Please advice. Many thanks.
Give up on trying to have a reentrantmalloc. It's a bad idea. If you really need to allocate memory from signal handlers, usemmap, but even that is a bad design.
Is the address returned by malloc a virtual address or is it the actual physical address where the memory is allocated? Edit: I read somewhere "In some implementations, calling free() releases the memory back to the system and in others it is released back to the process". Does "releasing back to the system" imply t...
It's an address valid in the current process. Whether it's virtual address or physical address depends on the underlying platform.
I am using C programming language in Linux platform and my question is how can I know how much I allocated in heap memory and other useful information such as peak usage in the heap memory. Is there a standard C function for this implementation? Please advice. Many thanks.
Since you're working on Linux, I am assuming you're using the GNU C Compiler. A little searching on Google revealed these websites... GNU malloc statistics Summary of malloc related functions ...that give information about the heap stats, which hopefully should contain the data you're looking for. Good luck!
After reading a series of man pages and searching through google, I decided to post this question to the bright folks of stack overflow. I'm working on a basic Unix Shell and one of the requirements is that I have to implement a command to echo out the shell's pid in base 10 ASCII... Before I read this requirement, I...
Technically speaking, the numbers that are returned bygetpid()are in base two. :-) Seriously speaking, the requirement probably just means that the number should be displayed as a decimal number as opposed to, for example, a hexadecimal number. I would ask for clarification of that requirement though, since you had t...
Have a problem with fscanf() - it does not skip to the next word after reading 10 characters from the file ``` while(fscanf(TEXT_FILE,"%10s", str) != EOF) // reads up to 10 char into str ``` If it find the word that is greater than 10 characters, it will read 10 characters, store them into str, continue in the same ...
You're probably better off usingfgets()andstrtok(), or writing a little loop aroundfgetc()to do what you want.fscanf()is flexible, but doesn't solve every problem.
I understand that the fastest and the most lightweight binary at windows generate only msvc compiler Express edition of msvc is freehttp://www.microsoft.com/express/windows/ but how to use cl.exe instead of g++.exe? is it possible in common by using GNU make variables produce makefiles which will works with cl.exe ...
Of course you can.cl.exeis just another command line tool. However, the two compilers differ in more advanced usage, so it might be difficult to usecl.exeas a drop-in replacement forg++.
This question already has answers here:Closed12 years ago. Possible Duplicate:Why is sizeof an operator? Why issizeofsupposed to be anoperatorin C, & not afunction? Its usage seems similar to that of a function call, as insizeof(int). Is it supposed to be some kind of a pseudo-function?
Because it's not a function; it's not possible to write a function that can take a type as an argument and return its size! Note also thatsizeofis implemented at compile-time, and that the parentheses aren't necessary if you're using it on a variable.
I have a .bin file that contains records in CSV format what I want to do is assign each record in the bin file a sequence number. So the first record in the bin file would be assigned 0 and so on. These will be placed into a bianry index file such as (username, seq #). If I have the bin file already created with re...
You would read lines from file A, and write lines to file B. Keep a count of each line you read and use that to generate the sequence number column when writing to file B. To be honest, I would probably use Excel or a spreadsheet app if the file is already in CSV format
How does one begin writing drivers for Windows? Is there some sort of official DDK "Hello World" example out there? While I'm sure it will be way above my head at first, eventually I would like to create a simple MIDI driver, much like theMaple Virtual MIDI Cablewhere the MIDI messages come from a user application r...
You could take a look at my virtualMIDI-driver: www.tobias-erichsen.de/virtualMIDI.html This one does exactly what your are looking for. Tobias
I'm working on broadcast, and I'm failing pretty badly at even getting the thing to work. I know I have to do the setsockopt() call, but what is needed before that to ensure that the broadcast will go to every box on the network? I vaguely remember something about complementing the network address or something like th...
You don't need to use setsockopt(). A UDP packet sent to the special address 255.255.255.255 will be sent to all addresses on the local network. If the network you want to broadcast to is not local you need to use the broadcast address of that network (as per ivymike's comment), which by convention is normally (but n...
var1 must hold a string whether it is empty or not or my program will segfault. But gcc complains that the empty string literal is constant while var1 is not. The following is an example of what I am talking about. How can I fix this ? warning: assignment discards qualifiers from pointer target type ``` char *var1 ...
To assign a empty string, do something like this: ``` var1 = malloc(1); /* 1 byte */ var1[0] = '\0'; ```
I want to open port 5555 on my machine using UPnP to the world. Could you please provide me with such Java sample for any sutable Opensource library. I need A CODE SAMPLE like one I can give you for C# usingthis lib ``` using TCMPortMapper; private void Form1_Load() { PortMapper.SharedInstance.Start(); PortMappi...
Have you tried googling for "java upnp library"? My first hit was oneUPNPLibthat looks reasonable.sample for UPNP mappingwith same. there are also others: weupnpcling
I ran into this question while typingman 2 open. It says that there are two kinds of open, one with two args, and one with three! last time i checked we could not overload functions in C. How did they do this? did they write in C++? ``` int open(const char * pathname, int flags); int open(const char * pathname, int f...
No, they just used variadic function. ``` int open(const char * pathname, int flags, ...); ``` This makes the last argumentmodeoptional. The prototypes only show how the function should be used, not the actual interface. Of course, unlike real overloading, the compiler cannot type-check themodeargument, so the user...
I want to create a simple 3D editor program, and I don't like C++ windows programming. But I don't want to mess with managed code when using OpenGL, either. So, it is possible to create in native C++ a control which will host the OpenGL 3D drawing surface, with no other controls, and also with an interface (methods an...
It is also possible to use managed C++. I created a simple OpenGL control for WinForms which suits your requirements. You can find more info about ithere.
I'm writing a simple application in ANSI C. I am using GCC in a Unix environment. I have the following sample application: ``` //main.c #include "foo.h" int main() { int result; result = add(1,5); return0; } ``` Header: ``` //foo.h #ifndef FOO_H_INCLUDED #define FF_H_INCLUDED int add(int a, int b...
You need to compile both your source files together: ``` cc main.c foo.c -o main ``` Also, in this case,-oproduces an executable, so calling itmain.ocan be misleading. Yet another tidbit, though unrelated to the question: the#ifndefand#defineinfoo.hdon't match.
Why is it that I'm finding the size of int and long int are shown to be 4 bytes? Is it that the int is by default long int?
``` sizeof(short) <= sizeof(int) <= sizeof(long) ``` That's all you can count on. The rest is completely up to the implementation. In the olden days of DOS, 16 bit compilers usually has sizeof(int) == sizeof(short) == 2. On 32 bit systems, sizeof(int) is usually equal to sizeof(long) == 4. As a rule of thumb,intis th...
Not sure if it is a duplicate. Given a data structure having firstNintegers and nextNchars.A = i1 i2 i3 ... iN c1 c2 c3 ... cN. I need an in-place algorithm to rearrange the elements asA = i1 c1 i2 c2 ... iN cN.
Your problem is equivalent to transposing a 2xN matrix in-place. You can read the theory here:http://en.wikipedia.org/wiki/In-place_matrix_transposition Maybe in the special case of 2xN matrix a simpler algorithm exists, however I can't think of any. The general idea is to follow the cycles of the permutation.
I declared a Normal Structure In C: ``` typedef struct arr_struct{ int* original; int size; int first[size/2]; int second[size-(size/2)]; }; ``` when compile it gives me: test.c:11: error: ‘size’ undeclared here (not in a function) any explanation?
You can't define arrays based on a variable size. The size has to be known at compile time. You'll need to makefirstandsecondpointers and dynamically allocate them oncesizeis known.
Can local message-based sockets transfer messages up to the SO_SNDBUF/SO_RCVBUF limits, or where can the so-called 'fixed maximum length' be determined for a descriptor created withsocket(PF_UNIX, SOCK_SEQPACKET, 0)orsocket(PF_UNIX, SOCK_DGRAM, 0)?
fromman unix The SO_SNDBUF socket option does have an effect for Unix domain sock‐ ets, but the SO_RCVBUF option does not. For datagram sockets, the SO_SNDBUF value imposes an upper limit on the size of outgoing data‐ grams. This limit is calculated as the doubled (see socket(7)) opt...
I have C program I compile withmingwon Windows. It works fine but requiresMSVCRT.DLL. I want to link that statically (like I can do in Visual Studio). Is this possible? I tried-staticflag togccand it didn't make any change. What about C++ program using also standard C++ library?
I believe that MinGW doesn't use the static runtime library for copyright reasons. You can maybe try to use newlib (http://sourceware.org/newlib/) to create an executable that doesn't link tomsvcrt.dll
Should I put the includes in the header file or the source file? If the header file contains the include statements, then if I include that header file in my source, then will my source file have all of the included files that were in my header? Or should I just include them in my source file only?
Only put includes in a header if the header itself needs them. Examples: Your function returns typesize_t. Then#include <stddef.h>in theheaderfile.Your function usesstrlen. Then#include <string.h>in thesourcefile.
I have a program like this ``` int main(){ char c; int i; /* counter */ double d; return 0; } ``` if I want to comment out char, int and double, and just have return uncommented, can I do it? the comment that's already there stops the comment.. Is there an easy/fast way to comment that out?
``` int main(){ #if 0 char c; int i; /* counter */ double d; #endif return 0; } ``` Not strictly a comment, but the effect is what you want and it's easy to revert. This also scales well to larger code blocks, especially if you have an editor that can match the start and end of the#if..#endif.
Seems all compilers can deal with both c and c++,like gcc ,msvc... Is it because these 2 languages are exactly very much alike?
Actually, GCC (GNU Compiler Collection) has two different front-ends,gccandg++. To specify C++, you can also use a .cpp (or a few others) extension, or-x c++, when executinggcc. However, this requires extra options (like linking in the C++ standard library). cl, Microsoft's C++ compiler, does not support modern C. ...
What is the correct way to work out how many bytes an int is? and how do I write an int to a file descriptor? Here is a mock code sample which might make clear what I am trying to achieve: ``` char *message = "test message"; int length = strlen(message); int fd = open(file, O_CREAT|O_RDWR); write(fd, length??, ??); ...
sizeof(length)goes in the field. It is preferable over usingsizeof(int)in case you ever change the type oflengthin the future. sizeofexpresses the, well, size of a data type in multiples ofsizeof(char), which is always 1.