question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I want to send a UDP packet to a camera from the PC when the PC resumes from sleep. Since it takes some time (unknown) to the network interface to become alive after the PC resumes, I keep sending packets to the camera in a loop. When the camera receives the packet, it sends an acknowledge signal to the PC.
My problem... |
UseMSG_DONTWAITflag passed torecvfromfunction. It enables non-blocking mode. If the operation would block this call returnsEAGAINorEWOULDBLOCKerror code.
|
I am not at a computer so cannot test this at the moment but have some code to review. I'm still somewhat in a C++ mindframe unfortunatley.
So, when a typedef is declared within a C source file what is its scope? I am aware that to make functions and variables only available within the same translation unit you need ... |
Typedefs are declarations. If you have a typedef in a C file, no other C file will be aware of that since they are compiled indepedendly of each other.
For a typedef in a header, it will of course be visible from all C files that include it.
|
How can I find that an IP address is a LAN IP address or WAN IP address? I am writing a C API in Windows.Thanks
|
Most likely, what you want to determine is whether the address is a global address, or aprivate address. The wikipedia article lists the address blocks that are reserved for private use.
|
I am interested in using the SSE vector instructions of x86-64 with gcc and don't want to use any inline assembly for that. Is there a way I can do that in C? If so, can someone give me an example?
|
Yes, you can use theintrinsicsin the *mmintrin.h headers (emmintrin.h,xmmintrin.h, etc, depending on what level of SSE you want to use). This is generally preferable to using assembler for many reasons.
```
#include <emmintrin.h>
int main(void)
{
__m128i a = _mm_set_epi32(4, 3, 2, 1);
__m128i b = _mm_set_epi... |
I have a dll file written in C# that is in the same solution as my application which is written in C++ with some files set to compile under the /cli flag. I'd like to load the WPF form inside my C# dll and display it in the C++ /cli application.
I already have my C++ application configured to display WPF content, as ... |
If you added the control reference to your CLI project, you should be able to have access to your control; having application handle useApplicationHandle->Run(YourWindow)method.
|
This question already has answers here:How to prevent GCC from optimizing out a busy wait loop?(9 answers)Closed3 years ago.
I am looking over some code to review and have come across a busy wait as such:
```
int loop = us*32;
int x;
for(x = 0;x<loop;x++)
{
/*do nothing*/
}
```
I seem to recall reading th... |
The answer is yes, the compiler can optimize out the loop.
Use thevolatilequalifier to avoid the optimization:
```
int loop = us * 32;
volatile int x;
for (x = 0; x < loop; x++)
{
/*do nothing*/
}
```
If you are programming in the embedded world read the documentation of your compiler as they usually prov... |
I need to create a dump file when there is an exception.
Is it possible to do so without using__try{...}and__except(e){...}?
Is there a way to create a callback function or register an action waiting for a system crash?
Thanks in advance.
|
Yes, you can usesignalto register a callback for a specific signal, including exceptions.
|
I'm new to C and experimenting with structs. After I've created a struct, is it possible to reassign it with curly brackets?
```
typedef struct {
int height;
int age;
} Person;
int main (void)
{
Person bill = {100,35};
bill = {120,34}; // error: expected expression before ‘{’ token
bill = Person ... |
Not directly, but C99 has compound literals for that
```
bill = (Person){120,34};
```
you could even do things more readable by using designated initializers like
```
bill = (Person){ .height = 120, .age = 34, };
```
|
I have something like this
```
char string[]="My name is %s";
printf("%s",string,"Tom");
```
I expect the output to beMy name is Tombut I am gettingMy name is %s
I tried escaping the%character, but it dint work.
What's going wrong here? How shall I have a%sinside a%s?
|
Try something like this
```
printf(string,"Tom");
```
The problem with your method is this -
As soon asprintfsees%sformat specifier in your format string, it assumes that the next argument in list is a string pointed to by a character pointer, retrieves it and prints it in place of%s. Now,printfdoesn't do arecursi... |
This is the only way to test if the return string is empty. Each fails in the other's architecture. The question is why? Why does!=NULLfail on x86 and_tcslen(*sDateOut)>0fail on x64?:
```
BOOL FormatDate(TCHAR *sIn, TCHAR **sOut) {
free(*sOut);*sOut=NULL; // Clear
...
if (condition1)
*sOut = calloc(length,sizeof... |
If you want to check for an empty string you should compare the first character with'\0',notNULL.
The reason for this is becauseNULLis supposed to represent a null pointer - it's actual value may not actually be zero.
Now back to the example, if you want to test ifTCHAR **sOutis a valid pointer to an empty string ... |
I need to create a dump file for a customer program written in C.
I saw that there is a minidump for windows, is it working only on C++ ?
Is there any other solution for C language?
Thank you for your time.
|
See this excellent tutorial:http://www.debuginfo.com/articles/effminidumps.html. It uses Win32 APIMiniDumpWriteDump, so its pure C.
|
see
i havemainActivitywhich callstempActivity
Now inside tempActivity i call some native method and malloc some data .. so now when user
1> come back from tempActivity to mainActivity or
2> exit from whole application
i need to call one clean up function which free all data malloc in native method so how can i i... |
Ok, i think the question is about how to free the memory that is being allocated usingmalloc()inside native code.
I had the same requirement in one of my Projects. I did it in the following way.
InsideonStop()oronDestroy(), I did a native call, which I have used tofree()the allocated memory. This I think is the best... |
I want to access the first array element after a loop completes executing.
I have an array that stores some numbers like 1,2,3,4,5. The array is always initialized with index 0 but I'm not using 0th index to store anything.
So what I want is using indexes in ring fashion like1-2-3-4-5-1I can achieve this if I use ar... |
You can subtract one, do%, and add one back:
```
a[((i-1)%ARRAY_LEN)+1]
```
This illustrates a problem of fighting the convention: instead of a simple%operation, you need a subtraction, a%, and an addition. Tather than fighting the C/C++ convention, it's best to embrace it for more efficiency and readability by othe... |
Quick one. Are the following equivalent? And are any of them more economical or "correct" than the others?
while (x==y) {},while (x==y) ;&while (x==y);.
Note the white space between the closing expression bracket and the semicolon in the second one and not in the third.
I have tended to use the first one in the pas... |
There's no difference between the second and third one.
The only difference for the first is readability - you're explicitly stating you want an infinite loop, not that you have a typo (extra;).
|
```
static char* theFruit[] = {
"lemon",
"orange",
"apple",
"banana"
};
```
I know the size is 4 by looking at this array. How do I programmatically find the size of this array in C? I do not want the size in bytes.
|
```
sizeof(theFruit) / sizeof(theFruit[0])
```
Note thatsizeof(theFruit[0]) == sizeof(char *), a constant.
|
Is it possible to adapt unique_ptr for plain c?
Perhaps if there is a way of simulating calls to a home made "constructor/destructor" when calling malloc/free?
Is it doable? Or is it just a silly idea?
|
The whole point of a "smart pointer" is to do certain tasks automatically on destruction. Since C doesn't have destructors there's no way to accomplish this except with explicit function calls - but that's how you deallocate memory in C already.
You could possibly make a list of pointers that need to be freed and do ... |
What is the difference between a pointer and bucket pointer?What is bucket pointer in C/C++?What are the advantages and drawbacks of using them?
|
Usually the term bucket refers to a subcontainer in a hash table or hash container. Elements that have the same hash code are stored in the same bucket. A bucket could be implemented as a pointer to some storage such as a raw array, the head of a linked list, or a pointer to an implementation class. A pointer could... |
I have a const char* variable which may have a value like "OpenStack:OpenStack1". I want to tokenize this const char* using strtok where the delimiter(which is of a const char* type) is ":" . But the problem is strtok is of following type:
char * strtok ( char * str, const char * delimiters );
Which means I can't use... |
Since strtok actually writes to your string, you need to make a writable copy of it to tokenize;
```
char* copy = strdup(myReadonlyString);
...tokenize copy...
free(copy);
```
|
I was under the impression that the math library is linked statically because-l namelinks tolibname.a, however if I try to compile with the-staticflag, suddenly GCC can't find the math functions.
Does this means that math is not necessarily linked statically? Or is something else is going on here?
|
If it would compile statically you would writegcc libname.ainstead ofgcc -l libname.
And to your question, yes math library is linked dynamically.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Why isn't sizeof for a struct equal to the sum of sizeof of each member?
Why the size of a structure is not equal to size of its members? What I can do to reduce them?
Say I have a structure `
```
struct a{
int a;
int b[10];
char a;
}
`... |
Because of the padding that can appear between and after structure members because of alignment.
You can pack structure members with gcc using thepackedattribute:
```
struct a {
int a;
int b[10];
char a;
} __attribute__((packed));
```
The amount of storage will be less but the code will also be potentia... |
see i have native function in nativeLib
```
public native int [] getArrayNative();
```
which i am using like this
```
private static int[] DEMO_NODES;
DEMO_NODES = nativeLib.getArrayNative();
```
in c code it has
```
JNIEXPORT jintArray JNICALL Java_com_testing_NativeLib_getArrayNative
(JNIEnv *env, jobject ... |
UseSetIntArrayRegionto fill the array,jintArrayist just some magic
internal structure, nothing you can access using indices.
Prototypevoid SetArrayRegion(JNIEnv *env, array,
jsize start, jsize len, *buf);
|
I can see from theGMP official documentation:
**void mpn_copyi (mp_limb_trp, const mp_limb_ts1p, mp_size_t n)Copy from {s1p, n} to {rp, n}, increasingly.
**void mpn_copyd (mp_limb_trp, const mp_limb_ts1p, mp_size_t n)Copy from {s1p, n} to {rp, n}, decreasingly.
However, I don't understand whatincreasinglyanddecreas... |
Usethe source, Teabee.
```
void
mpn_copyi (mp_ptr rp, mp_srcptr up, mp_size_t n)
{
mp_size_t i;
up += n;
rp += n;
for (i = -n; i != 0; i++)
rp[i] = up[i];
}
```
And decrementing:
```
void
mpn_copyd (mp_ptr rp, mp_srcptr up, mp_size_t n)
{
mp_size_t i;
for (i = n - 1; i >= 0; i--)
rp[i] = up[i]... |
I know we can check through ethtool whether TCP segmentation has been offloaded. But I need to get this info from my own code. What is the simplest way to do this? Is there a flag that I can check for this?
Thanks
Supreeth
|
You can use the sameioctl()call as ethtool does.
Just look at the source code for ethtool to figure out how it does it:
```
struct ethtool_value eval;
eval.cmd = ETHTOOL_GGSO;
ifr->ifr_data = (caddr_t)&eval;
err = ioctl(fd, SIOCETHTOOL, ifr);
if (err)
perror("Cannot get device generic segmentation offload se... |
At run time, how can I create a thread ?
I will take # of thread from standard input--terminal-- then I will create thread according to this number. But, How ?
```
Ex:
input : N, N is integer
in main function
create N thread
```
EDIT : platform Linux
|
Yes, threads (if we assume that we are using pthreads) are created with the callpthread_create, and you can call that from a loop.
Here is the start of a C function that creates N threads:
```
int start_N_threads(int N) {
pthread_t threads[N];
printf("Starting %d thread(s)...\n", N);
for (int i = 0; i < ... |
This program will create a child process, the child process will wait for an ALARM signal, when this signal arrives after 3 seconds, the f function will grab the parent process ID, and send a SIGINT signal to kill it, so the child will kill the parent after 3 seconds
```
#include <stdio.h>
#include <unistd.h>
... |
Stop stomping onfwith your variable.
|
I get a warning when running my program under valgrind:
```
==24214== Warning: silly arg (-1) to malloc()
```
How can I determine what call tomalloc()is faulty? Is there a way I can do this without recompiling?
The program is compiled with-g(debug) and without-s(strip).
|
After a modicum of experimentation on a relatively antique RedHat Linux with Valgrind version 3.2.1, it appears that it does not produce a more precise warning. Further, even Valgrind 3.7.0 on Mac OS X 10.7.3 doesn't do a better job of identifying the erroneous call.
Test code:
```
#include <stdlib.h>
#include <std... |
Does anyone know of a library or framework to salt and hash a password in C? How would I go about doing this in a program?
|
I would definitely go withOpenSSL. Please, when it comes to encryption, don't try and roll your own, or just find something someone posted on the Internet. Go with something like OpenSSL that is verified, and trusted by millions every day. Home-brew and improperly implemented encryption is in my opinion a leading caus... |
Well, I need develop applications for Windows mobile 6.1/6.5 and I'm looking for how to do this using C language programming. I heard that it's possible, but so far not found anything about, just support for C++/CLI programming language on older versions of VS.
|
UseeMbedded Visual C++ 4.0.
It is free, too.
Just an FYI, though: IMO: Visual Studio 2008 is MUCH faster at getting stuff done.
|
Just a quick question. I have a network C application (TCP server) which has multiple worker threads(Pthreads).Each worker thread uses aselectsystem call and each thread has the listeningsocket descriptoradded to its select set. So effectively each worker thread listens for incoming connections, and only one thread at... |
You can share sockets and file descriptors between different threads. That's what most servers do.
|
Is it possible to determine if a pthread_t struct I have declared is unused? I have an array of pthread_t structs, and at the end of my program I call pthread_join() on each, but if some of them are never used I don't want to call pthread_join() on them. What's the best way to tell if a pthread_t struct has gone unuse... |
Thepthread_tobject passed topthread_join()must refer to a joinable thread. So you need to track this yourself - keep a flag alongside the pthread_t object to track whether it's used (maybe package the flag in a struct with the pthread_t).
Just keep in mind that in addition to not having used thepthread_tobject yet, i... |
My .c programme using glut creates an object and maps a texture onto that object. This object can then be manipulated by the user. When the object is scaled up then scaled down it moves outside of the window and out of view. How do i make sure the object stayes central when scaling or an alternative cant move outside ... |
It sounds as though the scaling operation is not scaling the object from the objects central position which will then cause the object to move away from its origin.
Make sure that you perform the scaling operationbeforeany translation.
|
In an extension, what can I do to avoid the crash of the php engine when zval string is allocated by myself ?
```
..
// will do implicitly ZVAL_STRING("tmp", "/tmp", 0);
//
SET_VAR_STRING("tmp", "/tmp");
..
php_embed_shutdown(TSRMLS_C); // GPF !!
```
Any ideas?
|
Change it to:
```
SET_VAR_STRING("tmp", estrdup("/tmp"));
```
|
How can I add an error to the perror stack?
here is an example of what I want
```
#include <stdio.h>
#include <stdlib.h>
int Div (int a, int b, int * c) {
if (b == 0) {
// add to perror: "cannot divide by zero!"
return 0;
}
*c = a / b;
return 1;
}
int main () {
int n;
if (!Div(2, 0,... |
There is no standard (or nonstandard, on the systems I'm aware of) way to add newerrnovalues; you can assign toerrnoto use existing values, but this is not a good idea for anything not part of the standard library.
|
I'm trying to set the cursor to a watch. The problem is that gdk_set_cursor() requires a gdk_window.
How do I get the gdk_window of a gtk_window in C? I've seen examples for gtkmm and pygtk but I can't find the corresponding C function.
|
```
GdkWindow *gdk_window = gtk_widget_get_window(GTK_WIDGET(gtk_window));
```
or, pre GTK 2.14, but now disallowed:
```
GdkWindow *gdk_window = gtk_window->window;
```
|
Is it guranteed that the string literals are stored adjacent in the memory?
Therefore does the below necessarily get an outputhellohello
```
printf(3 + "%d");
printf("hello");
```
|
No, string literals are stored wherever your compiler fancies. The fact that you declared two of them in consecutive lines is irrelevant. You can make no assumptions about where the compiler will store them.
The compiler can do all sorts of things. For example, if you write the following code
```
printf("hello");
pr... |
This program will create a child process, the child process will wait for an ALARM signal, when this signal arrives after 3 seconds, the f function will grab the parent process ID, and send a SIGINT signal to kill it, so the child will kill the parent after 3 seconds
```
#include <stdio.h>
#include <unistd.h>
... |
Stop stomping onfwith your variable.
|
I get a warning when running my program under valgrind:
```
==24214== Warning: silly arg (-1) to malloc()
```
How can I determine what call tomalloc()is faulty? Is there a way I can do this without recompiling?
The program is compiled with-g(debug) and without-s(strip).
|
After a modicum of experimentation on a relatively antique RedHat Linux with Valgrind version 3.2.1, it appears that it does not produce a more precise warning. Further, even Valgrind 3.7.0 on Mac OS X 10.7.3 doesn't do a better job of identifying the erroneous call.
Test code:
```
#include <stdlib.h>
#include <std... |
Does anyone know of a library or framework to salt and hash a password in C? How would I go about doing this in a program?
|
I would definitely go withOpenSSL. Please, when it comes to encryption, don't try and roll your own, or just find something someone posted on the Internet. Go with something like OpenSSL that is verified, and trusted by millions every day. Home-brew and improperly implemented encryption is in my opinion a leading caus... |
Well, I need develop applications for Windows mobile 6.1/6.5 and I'm looking for how to do this using C language programming. I heard that it's possible, but so far not found anything about, just support for C++/CLI programming language on older versions of VS.
|
UseeMbedded Visual C++ 4.0.
It is free, too.
Just an FYI, though: IMO: Visual Studio 2008 is MUCH faster at getting stuff done.
|
Just a quick question. I have a network C application (TCP server) which has multiple worker threads(Pthreads).Each worker thread uses aselectsystem call and each thread has the listeningsocket descriptoradded to its select set. So effectively each worker thread listens for incoming connections, and only one thread at... |
You can share sockets and file descriptors between different threads. That's what most servers do.
|
Is it possible to determine if a pthread_t struct I have declared is unused? I have an array of pthread_t structs, and at the end of my program I call pthread_join() on each, but if some of them are never used I don't want to call pthread_join() on them. What's the best way to tell if a pthread_t struct has gone unuse... |
Thepthread_tobject passed topthread_join()must refer to a joinable thread. So you need to track this yourself - keep a flag alongside the pthread_t object to track whether it's used (maybe package the flag in a struct with the pthread_t).
Just keep in mind that in addition to not having used thepthread_tobject yet, i... |
My .c programme using glut creates an object and maps a texture onto that object. This object can then be manipulated by the user. When the object is scaled up then scaled down it moves outside of the window and out of view. How do i make sure the object stayes central when scaling or an alternative cant move outside ... |
It sounds as though the scaling operation is not scaling the object from the objects central position which will then cause the object to move away from its origin.
Make sure that you perform the scaling operationbeforeany translation.
|
In an extension, what can I do to avoid the crash of the php engine when zval string is allocated by myself ?
```
..
// will do implicitly ZVAL_STRING("tmp", "/tmp", 0);
//
SET_VAR_STRING("tmp", "/tmp");
..
php_embed_shutdown(TSRMLS_C); // GPF !!
```
Any ideas?
|
Change it to:
```
SET_VAR_STRING("tmp", estrdup("/tmp"));
```
|
I want a function which will block until an interface is bound/unbound for OS X (i.e. the equivalent of Windows'NotifyAddrChange. Anyone know how to do this?
|
You are looking forSCNetworkReachability, take a look atthe reference.
Note that you need to include<SystemConfiguration/SystemConfiguration.h>to use it.
|
Why does a chararrayhave to end with a null character? Is there any reason that I have to add the null character to to everychararray ?
It seems that they get treated the same way.
|
A char array doesn't have to be null terminated (standard library functions which don't depend on this includememcpy,memmove,strncpy-- badly named this latest one --,printfwith the right format string).
A NUL Terminated Character String (NTCS) needs by definition to be terminated by a NUL. It is the format expected ... |
I'm using the C-style GTK functions in C++ and I can't figure out how to set the cursor for the main window.
|
Usegdk_set_cursor()
(https://developer.gnome.org/gdk3/stable/gdk3-Windows.html#gdk-window-set-cursor)
on a GdkCursor created bygdk_cursor_new()
(https://developer.gnome.org/gdk3/stable/gdk3-Cursors.html)
|
While iterating through socket file descriptors, how can I check if one of them is from a passive socket (listening for connections)?
|
This can be checked withgetsockopt(SO_ACCEPTCONN). For example:
```
#include <sys/socket.h>
int val;
socklen_t len = sizeof(val);
if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &val, &len) == -1)
printf("fd %d is not a socket\n", fd);
else if (val)
printf("fd %d is a listening socket\n", fd);
else
printf... |
I have text file with content as:
```
12345678901222344567
```
Then I used this code to read the content:
```
FILE * pFile;
int c;
char buffer [256];
pFile = fopen ("myfile.txt","r");
int a[50] = {0};
fread(a, sizeof(a[0]), 5, pFile);
fclose(pFile);
for (c = 0; c < 5; c++)
{
printf("%d\n", a[c])... |
You have a text file, but fread reads binary data. So you're storing the bytes from the file rather than the text of the file. Try using fread to populate your unusedbuffervariable instead and you should be able to get the textual string which you can then parse using e.g. sscanf(). Or you could stop using fread an... |
I am building source on Windows using Cygwin, I need to find places with memory leaks and possible memory leaks. I know about Valgrind used for memory leak detection in Linux.
Can Valgrind be used along with Cygwin so that it works in a Windows based environment?If yes can you please tell what configurations, etc. ar... |
No it'snotsupported.
Also, an obvious link:http://www.google.com/search?q=cygwin+valgrind
|
I have text file with content as:
```
12345678901222344567
```
Then I used this code to read the content:
```
FILE * pFile;
int c;
char buffer [256];
pFile = fopen ("myfile.txt","r");
int a[50] = {0};
fread(a, sizeof(a[0]), 5, pFile);
fclose(pFile);
for (c = 0; c < 5; c++)
{
printf("%d\n", a[c])... |
You have a text file, but fread reads binary data. So you're storing the bytes from the file rather than the text of the file. Try using fread to populate your unusedbuffervariable instead and you should be able to get the textual string which you can then parse using e.g. sscanf(). Or you could stop using fread an... |
I am building source on Windows using Cygwin, I need to find places with memory leaks and possible memory leaks. I know about Valgrind used for memory leak detection in Linux.
Can Valgrind be used along with Cygwin so that it works in a Windows based environment?If yes can you please tell what configurations, etc. ar... |
No it'snotsupported.
Also, an obvious link:http://www.google.com/search?q=cygwin+valgrind
|
Two use cases for which I would considershortcome to mind:
I want an integer type that's at least 16 bits in sizeI want an integer type that's exactly 16 bits in size
In the first case, sinceintis guaranteed to be at least 16 bits and is the most efficient integral data type, I would useint. In the second case, sinc... |
There is never a reason to useshortin a C99 environment that has 16-bit integers; you can useint16_t,int_fast16_torint_least16_tinstead.
The main reasons for usingshortis backward compatibility with C89 or older environments, which do not offer these types, or with libraries usingshortas part of their public API, for... |
How are you supposed to programatically detect when the remote modem on your call hangs up? I am writing a C program which interfaces with a SoftModem device/dev/ttySL0in Ubuntu linux. I am able to configure the modem using Hayes AT commands and communicate with the remote modem. However, I haven't been able to determ... |
This is a hardware signal on modems, the Carrier Detect (CD) line. You'll need to monitor it to know that the connection was lost. Basics in linux are described inthis how-to, you obtain the signal state with ioctl() using the TIOCM_CAR command.
|
I want to set a signal handler in my application, so that the kernel sends a signal whenever it handles a page fault trap. Ofcourse I can use theSIGSEGVsignal handler, but what I'm really interested in is to catch the page faults which occur on copy-on-write. For example after a fork (not followed by exec), the origin... |
page faults are interrupts handled by do_page_fault()
```
http://www.stillhq.com/pdfdb/000446/data.pdf
```
Signals also generate an interrupt. The difference is that the page fault interrupt is vectored to the code. There is an explanation of what the code does. IMO, always generating another interrupt in a an in... |
I have a library which consumes aFILE *and outputs data to anotherFILE *.
I want to handle both the input to this library and the output from this library in memory without reading/writing to/from a file on the disk.
We're doing this in iOS - so running the library as a separate app and usingstdin/stdoutisn't (as fa... |
Because ObjC is a superset of C, all you have to do is#import/#include <stdio.h>to gain access to thefunopen()which in itself contains the functionsreadfn,writefn,seekfn, andclosefn. And fwopen which has an example showing how to write to two streams at this otherSO question.
Mac OSX and iOS don't includefmemopenando... |
With lock files I mean: Create a file to lock a resource and delete it when releasing it again.
|
Directly from the man page:
```
NOTES
flock() does not lock files over NFS. Use fcntl(2) instead: that does work over NFS, given
a sufficiently recent version of Linux and a server which supports locking.
```
I'm not saying using lock files is the better option over NFS, though.
|
I get an error with this istruction:
```
dp = opendir ("%APPDATA%/.");
output:
Couldn't open directory: Mo such file or directory.
```
but I don't get an erro with this istruction:
```
dp = opendir ("C:/Users/xrobot/AppData/.");
output:
.
..
Local
LocalLow
Roaming
```
Why ?
|
opendirdoesn't expand meta variables like%APPDATA%, the shell does. So such things work from the command line, but not from a program. In your program, you have to use an absolute or relative path.
You can probably obtain the required path withgetenv(),
```
const char *appData = getenv("APPDATA");
if (appData) {
... |
I need in my program to call strtok twice, one inside the other. The problem I've got is that the first strtok cannot resume the loop after executing the inside strtok and it loses the pointer of the first char.
To explain more here is an example:
main:
```
tokens = strtok (stmt, ":");
while (tokens != NULL... |
strtokis not reentrant (which means you cannot call the function again before it finishes its previous execution), you have to usestrtok_r(which is reentrant) instead.
|
I have several struct: edge, vertex, graph in my library.
I want to hide body of that structs from user (user have to use API), so in header file (eg. edge.h) I've just put:
```
typedef struct edge edge_t;
```
And definition of edge struct is in edge.c
```
struct edge {...};
```
That works fine, but I want don't w... |
If you need to use the structure from other source files, they need the complete definition of the structure. So the solution is to putstruct edge { /* ... */ }in the header file as well, and include the header whenever you need to.
|
My .c programme gives an object a 'name' when its created. I need to be able to excute different tasks depending on that name. I very new to this and have tried a couple of ways with no success. Here is what I had come up with..
```
if (name == "james"){
//Do a bunch of stuff
}
if (name == "tom"){
//... |
if 'name' is a C++ string, what you have written should work fine. If it's achar[]orchar *, usestrcmp.
|
Intypedef and struct namespaces in C vs C++, one of the comments seems to imply that exposing somestruct foois preferable to using typedef along the lines of...
```
typedef struct foo foo;
```
...and then usingfooinstead ofstruct foothroughout the API.
Are there any downsides to the latter variant?
|
The only downside(*) is that it hides the fact thatfoois a struct, and not an alias for some builtin type.
Note(*): it's matter of taste whether this is a downside for you.
It's good for total opaqueness (see the first comment below).To see why some people think this is a downside, check thelinux kernel coding style... |
I have made a small program in c# called Registry.exe.
Now i my c++ program i want to call this Registry.exe is there a way to do it.
User cannot give any inputs the call is to be based on conditions
|
You cann simply use
system("Registry.exe");
|
When I try to get the attribute of URL in a test XML:
```
<Test> <Item URL="http://127.0.0.1?a=1&b=2"/>
</Test>
```
After I call: attr=xmlGetProp(cur, BAD_CAST "URL");
The libxml2 give a message: Entity: line 1: parser error : EntityRef: expecting ';'
and return value of attr is "http://127.0.0.1?a=1=2"
How can I... |
You cannot get the “correct” URL here because the XML file is notwell-formed. the&should have been written as&. You have to ask the creator of the XML file to create asyntactically valid, well-formed XML file.
XML isnotcreated by just putting strings together, they also have to be encoded properly.
|
I am generating an XML file using libxml2. In one of the tags i want to put the current time in"dd mm yyyy hh mm sec"format.
My dev environment is C/LINUX.
Thanks !
|
Usestrftime. Check the manual page for details.
|
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... |
I would suggest using c++ due to it having an object oriented side, but the opengl is cross platformhttp://www.opengl.org/resources/bindings/
|
Is it possible to have an overflow (wrap around) with a double or a float? What will happen if the maximum (or minimum) value is reached on x86 or x64 hardware?
|
On an IEEE-754 compliant system, overflow results in a special "infinity" (or "minus infinity") value, beyond which any further increment will have no effect.
|
Instead of
```
cardNumber = j+1;
deck[i][j] = cardNumber;
theDeck[k] = cardNumber;
```
is it valid to just say
```
deck[i][j] = theDeck[k] = cardNumber;
```
to assign cardNumber to both deck and theDeck at the same time??
|
Yes, it is. The assignment operator returns a value.
|
I have made a small program in c# called Registry.exe.
Now i my c++ program i want to call this Registry.exe is there a way to do it.
User cannot give any inputs the call is to be based on conditions
|
You cann simply use
system("Registry.exe");
|
When I try to get the attribute of URL in a test XML:
```
<Test> <Item URL="http://127.0.0.1?a=1&b=2"/>
</Test>
```
After I call: attr=xmlGetProp(cur, BAD_CAST "URL");
The libxml2 give a message: Entity: line 1: parser error : EntityRef: expecting ';'
and return value of attr is "http://127.0.0.1?a=1=2"
How can I... |
You cannot get the “correct” URL here because the XML file is notwell-formed. the&should have been written as&. You have to ask the creator of the XML file to create asyntactically valid, well-formed XML file.
XML isnotcreated by just putting strings together, they also have to be encoded properly.
|
I am generating an XML file using libxml2. In one of the tags i want to put the current time in"dd mm yyyy hh mm sec"format.
My dev environment is C/LINUX.
Thanks !
|
Usestrftime. Check the manual page for details.
|
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... |
I would suggest using c++ due to it having an object oriented side, but the opengl is cross platformhttp://www.opengl.org/resources/bindings/
|
Is it possible to have an overflow (wrap around) with a double or a float? What will happen if the maximum (or minimum) value is reached on x86 or x64 hardware?
|
On an IEEE-754 compliant system, overflow results in a special "infinity" (or "minus infinity") value, beyond which any further increment will have no effect.
|
Instead of
```
cardNumber = j+1;
deck[i][j] = cardNumber;
theDeck[k] = cardNumber;
```
is it valid to just say
```
deck[i][j] = theDeck[k] = cardNumber;
```
to assign cardNumber to both deck and theDeck at the same time??
|
Yes, it is. The assignment operator returns a value.
|
Is it possible to change the virtual memory page size? I'm asking this because in theX86_64 part of the MMU article on wikipedia, it talks about different page sizes. If the page size can indeed be changed, how it is changed?
|
On x86_64 you can explicitly request 2 MiB pages instead of the usual 4 KiB pages with the help ofhugetlbfs. On modern kernels with transparent huge page support a small pages can automagically concatenated to huge pages in the background, given that the memory fragmentation isn't to big and enough memory is still fre... |
I'm a real begginer in GTK+ programming, and I have trouble understanding the g_source_new() function.
I would like to handle my sockets using GTK events (new event when my socket is readable/writable, as using select).
If anybody could send me on a way, I'm completely lost...
PS: I don't want to use Gtk's socket m... |
GSource is poorly documented. The best you can do is browse the source and see how the timer and idle sources are implemented. Read the code of g_timer_add and g_idle_add.
|
i am trying to print a line from a text file then go to the next line and print that until there is no more lines left to print. This is what i have so far, but it only works the first time that i run the program.
```
void ReadFile(FILE *a)
{
char line[23];
while(fgets(line, 22, a) != NULL)
{
prin... |
You will need to reset thefile pointerback to the start if you want to do this multiple times with the sameFILEobject:
```
void ReadFile(FILE *a)
{
char line[23];
rewind(a);
while(fgets(line, 22, a) != NULL)
{
printf("%s\n", line); // Added new line
}
}
```
Reference.
|
After opening a file for writing:
```
FILE *file = fopen("./file", "w");
```
Can I assume the file was created immediately? Is it safe to call:
```
stat( "./file", info);
```
Or should I better:
```
fflush(file);
```
or
```
fclose(file);
```
beforehand?
Edit: Assume non NULL file after fopen call
|
Thefopen manual pagesays:
If mode is w, wb, a, ab, w+, wb+, w+b, a+, ab+, or a+b, and the file
did not previously exist, upon successful completion, the fopen()
function shall mark for update the st_atime, st_ctime, and st_mtime
fields of the file and the st_ctime and st_mtime fields of the parent
directory.
... |
could you say me what is the mistake in my following code?
```
char* line="";
printf("Write the line.\n");
scanf("%s",line);
printf(line,"\n");
```
I'm trying to get a line as an input from the console.But everytime while using "scanf" the program crashes. I don't want to use any std, I totally want to avoid using... |
You need to allocate the space for the input string assscanf()cannot do that itself:
```
char line[1024];
printf("Write the line.\n");
scanf("%s",line);
printf(line,"\n");
```
However this is dangerous as it's possible to overflow the buffer and is therefore a security concern. Usestd::stringinstead:
```
std::st... |
Given: The path of a file on a UNIX file system
How can I get the UUID of the device it is stored on, possibly with a library call from C, in a way that is the most portable amongst UNIX like system (including OS X)?
|
You can callint stat(const char *path, struct stat *buf)and the buf->st_dev will give to you the device's ID.
stat() is POSIX.1.
|
I am sending data over PC1 to PC2, both are Linux 2.6 kernel machines. This transfer will take a couple of hours. The ARP cache stale timeout is set to 50 seconds in PC1. So during data transfer, every 50 seconds the PC1 sends ARP request to PC2 (since the arp cache expires in PC1). But theoretically, since data trans... |
Get a new switch.
Really. Don't try to work around hardware issues by fooling around in the kernel.
If you really insist on getting this working, just set up static ARP entries. They don't time out.
|
I am trying to call route -n in cgic code but popen returns null. I tried with a simple C code and it works but when i put it in cgi it returns null.
```
printf("Content-type: text/html\r\n");
printf("\r\n");
....
..
stream = popen("route -n", "r");
while ( fgets(buffer, 100, s... |
If I'm looking into my linux box, I see thatrouteis located under/sbin/routeand is therefore not part of the$PATHfor standard users (while it's executable for them on my system).
catandnetstatare located under/bin/and therefore are part of the$PATH.
```
popen("/sbin/route -n", "r");
```
will bring up the process.
... |
I am working on an embedded system (ARM Cortex M3) where I do not have access to any sort of "standard library". In particular, I do not have access tomalloc.
I have a functionvoid doStuff(uint8_t *buffer)that accepts a pointer to a 512 bits buffer. I have tried doing the following:
```
uint8_t buffer[64] = {0};
doS... |
doStuff(buffer)shall be ok sincebufferis alreadyanuint8_t*.
Aside of this, you're closing one bracket too much after&bufferin your example.
Ifbufferis of variable size, you should pass the size intodoStufftoo, if it's of constant size, I'd also pass the size just in case that you change the size one day.
This bei... |
I am usingCode::Blockswith GCC 4.4.1 and I seem to be unable to print 64-bit signed integers from my C-code.
This code:
```
long long longint;
longint = 0x1BCDEFABCDEFCDEF; /* 2003520930423229935 */
printf("Sizeof: %d-bit\n", sizeof(longint) * 8); /* Correct */
printf("%llx\n", longint); ... |
See if%I64dhelps you.%lldis fine forlong long intbut things get really different sometimes on Windows IDEs
|
Here is the requirement:
The input is a PNG A and a PNG B, the output should be PNG A minus PNG B (dig a hole with PNG B's shape on PNG A). I think this should be a draw complement action, and I need some library or framework to do that.This framework should work with Xcode, and also can be used at various of plantfo... |
You can try this code:
```
UIImage *imgA = [UIImage imageNamed:@"pngA.png"];
UIImage *imgB = [UIImage imageNamed:@"pngB.png"];
UIGraphicsBeginImageContextWithOptions(imgA.size, NO, imgA.scale);
[imgA drawAtPoint:CGPointZero];
[imgB drawAtPoint:CGPointZero blendMode:kCGBlendModeDestinationOut alpha:1.0f];
UIImage *re... |
currently I have three web-cams connected to my laptop, the internal webcam and a two same company's external web-cam. I want to take input from the external web-cams for a single object simultaniously.
I am not very sure what should i do for that.Should I do
```
CvCapture* capture1=cvCaptureFromCAM(1);
CvCaptur... |
Start with a simple test that captures only from one camera. Then change the index number passed tocvCaptureFromCAM()until you can identify which indexes correspond to the webcams you are interested at.
This answeris a must read since it provides very interesting information related to this task, andthisshares some c... |
I am working on an assignment that deals with storing and sorting some data. I had an idea to create a simple data structure as follows:
```
struct names
{
char username[9];
linked list of structs
}
struct login
{
char ip_addr[16];
int count;
}
```
I have my linked-list of login structs working properly, however, ... |
Yes, put the header node pointer inside yournamesstruct.
|
I'm making a dynamic array withint*data type usingmalloc(). But the problems is, how to know end of array?
There no an equivalent to\0forint*data type,so, how to do this? Pass size as out parameter of function?
|
C doesn't manage array lengths, as some other languages do.
you might consider a structure for this:
```
typedef struct t_thing {
int* things;
size_t count;
} t_thing;
```
in use:
```
t_thing t = { (int*)malloc(sizeof(int) * n), n };
```
|
I have the following program:
```
#include <stdio.h>
#define STDIN 0
int main()
{
fd_set fds;
int maxfd;
// sd is a UDP socket
maxfd = (sd > STDIN)?sd:STDIN;
while(1){
FD_ZERO(&fds);
FD_SET(sd, &fds);
FD_SET(STDIN, &fds);
select(maxfd+1, &fds, NULL, NULL,... |
Theselectfunction only tells you when there is input available. If you don't actually consume it, select will continue falling straight through.
|
I want to send some complex objects from a Java client to C server via a TCP Socket.
How can I do that ?
|
Fundamentally the question is, "How to serialize/deserialize objects in a
language agnostic manner?" Specifically Java and C in your case. Since you'll
be sending this data over a network, it is also important to take care ofnetwork order/endiannessissues.
I assume you have access to both the the client and the ser... |
I need to do division using long double, on the order of 1/10^23, however the numbers get cut off when i check them using printf. Does anyone one know how I can see the full number? For example:
```
long double a = 1;
long double b = 3;
printf ("%Lf", a/b );
```
But I get:
```
0.333333
```
For example I would like... |
%fformat prints with 6 digits after the decimal point. You can use%.dfto print d digits. Or better yet, use%.dgto make large/small values readable as well.
|
This is a snippet of C code from a library:
```
typedef enum
{
/**
* @brief SDIO specific error defines
*/
SD_CMD_CRC_FAIL = (1), /*!< Command response received (but CRC check failed) */
SD_DATA_CRC_FAIL = (2), /*!< Data bock sent/received (CRC check Failed) */
SD... |
Yes, they are equivalent.
I don't know why the author chose to write it like that (although see the comments to this answer for some theories).
|
For normal file path, I can use stat and get size of it. When the path contains non-ascii names like C:\temp\sमानकe\app.log, it does not work.
```
int main(int argc, char * argv[])
{
struct stat FileAttrib;
if (stat(argv[1], &FileAttrib) < 0) {
printf("File Error Message = %s\n", strerror(err... |
Assuming you are using Windows, try usingGetShortPathNameWto get the short path name (if it exists), and then pass the short name tostat().
|
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... |
You can use scanf onideone.com, however I'm not sure about-lm.
That said, I can't recommend it for serious work.
|
A few websites claim that the string type is a scalar. As I understand it, scalars are single-value types, as opposed to array types. But isn't a string essentially an array of chars? So why would it be a scalar?
EDIT: If the answer/explanation differs from C to C++, I'd like explanations to include both languages. I... |
char*andconst char*are scalar types, whereaschar[n]andconst char[n]are not.
Arithmetic types, enumeration types, pointer types, pointer to member types,std::nullptr_t, and cv-qualified versions of these types are collectively calledscalar types. (3.9 Types [basic.types] §9)
|
My program read some text data from network, something like:Hello \033[1;34mworld\033[0m and bla bla bla!!!\n".
When program output this string using prinf, the word "world" is blue. But when I'm using ncurses interface with wprintw or addch, I see the original string with escape sequences.
Does it mean that printf ha... |
No, your terminal handles the escape sequences. The phenomenon you're seeing comes from the fact that ncurses' whole purpose is to keep track of the intended terminal contents and be able to repaint it, and as part of doing this it strips any escape sequences. It might provide an alternative function tointerpretthem a... |
Example : 2.3666%
And I am Using.
But Not Working..
```
float n = 2.3666;
NSLog(@"%f%",n);
```
|
You need toescape percent signs using%%
```
float n = 2.3666;
NSLog(@"%f%%",n);
```
|
If the file is .c MSVC will compile.
If it's .cpp it"cannot convert from 'void *' to 'unsigned char *'"
I'm using theMEMORY_BASIC_INFORMATION::BaseAddressinwindows.hwhich isvoid*, assigning it to achar*so I can see the actual address you know?
When I cast it to char*, and later back tovoid*(to use it in windows fun... |
In C++, you must use an explicit cast to convert avoid*to anything else:
```
void *vp;
unsigned char *cp = static_cast<unsigned char *>(vp);
```
This is indeed different from the situation in C, where avoid*can be implicitly converted to any other pointer type. The reverse situation is still as in C:
```
void *vp =... |
How can I "compile" Objective-C Code to (only) C-Code?There is a way to preprocess Objective-C in Xcode (Product -> Generate Output -> Generate Preprocessed File), but this is not what I'm looking for...
Thanks...
|
clang (the compiler front-end used by Xcode nowadays) has a-rewrite-objcoption built-in, which allows you to generate C++ code based on Objective-C (or Objective-C++) code.
Just don't ask me how to combine that with Xcode.
|
I have this code
whitespaces is a type int, so I can use the getchar function
```
do
{
...code...
whitespaces=getchar();}
while ( whitespaces != (EOF) || whitespaces!='\n');
```
but it doesnt exit the loop when i hit CTRL+Z (i am using windows 7)
what am I doing wrong?
EDIT : thank you, all of you...! very hel... |
You must use&&instead of||in thewhilecondition.
|
```
#include <stdio.h>
void main(){
char *str[]={"aa","bb"};
str[0][0]='h';
}
```
I receive a segmentation fault when executing this code. Does anyone know the reason?
Thanks in advance.
|
You are assigning to a location occupied by a string constant, an undefined behavior. If you know the max lengths of your strings, you can do this:
```
char ss[][3] = {"aa", "bb"};
```
It's not a precise equivalent, but it should work. If you do not know max length, or do not want to waste a few bytes here and there... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.