question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
Anyone know if ffmpeg does asynchronous file io? That is, the input file is read in a separate thread as to avoid io blocking the processing thread?
Basically what I want to figure out is whether or not i need to do calls to "av_read_frame" inside a separate thread (to avoid blocking) or if ffmpeg alrdy handles this ... |
You need to do it yourself. FFmpeg only has minimal thread awareness, and as icecrime said, the function signature obviously precludes doing it asynchronously.
|
I have a file saved as UTF-8, and i'm reading it like this:
```
ReadFile(hFile, pContents, pFile->nFileSize, &dwRead, NULL);
```
(pContents is a BYTE* of size nFileSize)
its just a small file with 100 bytes or so, contains text which i want to read into memory in wchar_t* format, so i can set the text of edit and s... |
MultiByteToWideCharto convert from UTF-8 to UTF-16 (wchar_t).WideCharToMuliByteto convert from UTF-16 to UTF-8.
|
```
gcc 4.5.1
Fedora 14 Linux
```
I have this static library that was build from a previous programmer. However, he has left the company and we don't have the source code. All we have is the header files*.hand thelibnet.astatic library.
When I am try and link this with our application. I get aincompatible linker err... |
An.aarchive is just a collection of objects, so why not:
```
ar x libnet.a
file someobj.o
```
That will give you an answer like:
```
someobj.o: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), not stripped
```
|
I currently have code that looks like
```
while (very_long_loop) {
...
y1 = getSomeValue();
...
x1 = y1*cos(PI/2);
x2 = y2*cos(SOME_CONSTANT);
...
outputValues(x1, x2, ...);
}
```
the obvious optimization would be to compute the cosines ahead-of-time. I could do this by filling an array w... |
If you're lucky, you won't have to do anything: Modern compilers do constant propagation for functions in the same translation unit and intrinsic functions (which most likely will include the math functions).
Look at the assembly to check if that's the case for your compiler and increase the optimization levels if ne... |
Is it possible to make the checkboxes in a list view control with LVS_EX_CHECKBOXES style tri-state (having BS_3STATE button style)? I'm using WTL but I'm OK manually sending messages around.
|
Yes, you need an ImageList with 3 images of a unchecked, checked and indeterminate checkbox. Call ListView_SetImageList() to assign the LVSIL_STATE image list. Manipulate LVITEM.state to display the kind of checkbox you want.
|
Is there any way to query ACLs on Linux programmatically? Given a file or directory, I have to check if an ACL exists for it and then find out the level of access granted to different users. All I could find on the net were thegetfaclandsetfaclcommand line utilities which are of no use to me. Also, what are the best p... |
They are in theacl.hheader. There are links out to each of the functions fromhere.
A few sample functions:
acl_create_entry- create a new ACL entryacl_delete_entry- delete an ACL entryacl_get_entry- get an ACL entry
The functions are in libacl.
|
Which one do you recommend for a commercial project with developers that need to have access to a particular part of repository only?
Development IDE is Eclipse
and Programming language is C/C++
Key features of the requirement is: Authoritative and ACL hierarchical access to repository
|
Git, combined with a "central" server managed withGitolite, can provide all the fine-grained control you need (per user/per group, with access to all or only some part of the repo, even to only some branches).
That being said, if your developers are more familiar with a CVCS like SVN, it might be wiser to use that kn... |
I'm looking for a way to easily debug C code in an Android NDK application using Eclipse. I've read ways to debug the app using gdb or something similar but what I want is a way to push messages to Eclipse somehow.
I'm looking for a solution that's as simple as using a print function in C and seeing it in the DDMS L... |
You can use the Android logging facilities:
```
#include <android/log.h>
#define APPNAME "MyApp"
__android_log_print(ANDROID_LOG_VERBOSE, APPNAME, "The value of 1 + 1 is %d", 1+1);
```
Make sure you also link against the logging library, in your Android.mk file:
```
LOCAL_LDLIBS := -llog
```
|
In the following code, is the behaviour undefined ?
```
#include<stdio.h>
int main()
{
printf(7+"%c","sundaram");
}
```
Its printing "aram". Can't understand how.
|
This is undefined behavior.
A string literal in C is a pointer to a a block of pre-initialized memory.By coincidence, your two string literals occupy adjacent blocks of memory.When you add7to the pointer to the first literal, you end up pointing into the middle of the next literal.
Your program's data is arranged in... |
I'm having trouble using bool as a type compiling with ndk-build:
```
bool test = true;
```
error:
48: error: 'bool' undeclared (first
use in this function)
Any ideas?
|
boolis not a built-in type in C. You need to#include <stdbool.h>to get it.
|
Does anyone know of any C parser library for .NET?
(I'm intending to parse C code into some form of object graph, so I can convert it to a different language.)
|
ANTLR can do what you'd like. It has a C preprocessor and ANSI C grammar.
https://github.com/antlr/grammars-v4
|
I'm looking for sample code on how to use the TMS3705 RFid transponder base station IC to communicate with the TMS37157 RFid device.
The TMS3705 datasheet is not very helpful - it only describes the physical interface.
Either sample code or a good description of how to construct/send a transmit packet and receive/par... |
The TMS3705 is used in thePaLFI Evaluation kit TMS37157. You find the reference to theFAQ.
|
I am currently looking into writing a plugin for mysql in C. I have been reading and studying MySQL 5.1 Plugin Development (http://www.amazon.com/MySQL-Plugin-Development-Sergei-Golubchik/dp/1849510601) which has been helping me out a lot. However I can't seem to find any examples that execute queries. I tried Googlin... |
I haven't used Mysql with C before, however you might want to take a look at these links:
http://dev.mysql.com/doc/refman/5.1/en/c-api-function-overview.htmlhttp://www.mysql.com/downloads/connector/c/
If you know MySql I think those links would be a good starting point at least.
|
Count amount of digits in a given number or input by the user.
|
Independent of programming language:
floor(log10(x))+1
where x is your number (>0).
If you want to handle 0 and negative numbers, I'd suggest something like this:
x == 0 ? 1 : floor(log10(abs(x)))+1
|
Can sombody explain how this works?
```
int x, y;
....
(some_condition ? x : y) = 100;
```
Is this intended to work or is is just a "blind" translation or the compiler (something likevec[10]equals10[vec])?
|
This is valid C++ and invalid C.
The result of a conditional expression can be (and in this case is) anlvaluein C++ refering to one ofxorydepending on whethersome_conditionevaluates totrue. In C++ eitherxis assigned the value 100 if some_condition istruewhen converted to abool, otherwiseyis assigned 100.
In C, the r... |
Could you please tell me the logic of usingsizeof data / sizeof *datainthis codeline 17?
```
...
unsigned char data[16];
...
size = fread(data, sizeof *data, sizeof data / sizeof *data, file);
...
```
Thanks
|
That's a common C idiom for "number of elements in an array".
Since an arraydecays to a pointerat the slightest provocation,*datais the first element of the array, and therefore it's dividing the total size of the array by the size of its first element, giving a count of elements.
There are any number of possible ob... |
Base on the answers i've got, i think this problem is kind of meaningless. Thanks for all your kind replies!
i want to get a binary number with its rightmost j bits set to 1 and others set to be 0. basically, there are two methods. i wanna know which of them is more efficient, or is there a more efficient way than th... |
Not sure if it's the answer you're looking for, but I'll bet it won't make more than a nanosecond of difference. :)
Or, to put it another way: Don't micro-optimize it unless that one-liner is the bottleneck in your code.
If you needotherforms of fast bit manipulation that might actually be slower, try looking at the... |
If I have several sets of numbers (just a 2D array where each row is a set):
```
[ 1, 3, -1, -1]
[ 2, 4, -1, -1]
[ 7, 8, 9, 10]
```
What would be an algorithm to create a list of sums (ignoring -1's)? the result for the above would be:
```
1+2+7,
1+2+8,
1+2+9,
1+2+10,
1+4+7,
1+4+8,
1+4+9,
1+4+10,
3+2+7,
3+2+8,
3+... |
For each number in the first list, generate all sums starting with that number and all sums recursively generated by applying the same method to all but the first list. When you have no lists left, that is the base case.
Pseudo-code:
```
function find_sums(lists):
if lists is empty:
return [""]
sums ... |
This question already has answers here:Closed12 years ago.
Possible Duplicate:Container Class / Library for C
I expect I'd be forced to use vectors, lists and sets for my C program. Should I invent those entities from scratch, or there is some kind of standard library for C as STL is for C++ ?
|
C doesn't have templates, so it might be difficult to implement those C++ collections in a generic way. I'm not aware of any libraries that implement those features in C.
If I were faced with such a situation, my first thought would be to isolate the parts
of my program that would benefit from C++ features, write t... |
I'm writing an app in C that requires MySQL interaction, so I downloaded the Connector/C archive from the official website, and it contains bin, lib and include folders, but I don't know where to install them.
I could copy the include files into my project folder, but where can I put the lib file so that my compiled b... |
This is confusing, isn't it.. don't know why they don't make this more clear.
The lib/ files go in /usr/local/lib
The include/ files go in /usr/local/include
The bin/ files go in /usr/local/bin
The /usr/.. directory isn't visible through finder afaik so you have to go at it via commandline. Best of luck
Also, in y... |
Is there any way to query ACLs on Linux programmatically? Given a file or directory, I have to check if an ACL exists for it and then find out the level of access granted to different users. All I could find on the net were thegetfaclandsetfaclcommand line utilities which are of no use to me. Also, what are the best p... |
They are in theacl.hheader. There are links out to each of the functions fromhere.
A few sample functions:
acl_create_entry- create a new ACL entryacl_delete_entry- delete an ACL entryacl_get_entry- get an ACL entry
The functions are in libacl.
|
Which one do you recommend for a commercial project with developers that need to have access to a particular part of repository only?
Development IDE is Eclipse
and Programming language is C/C++
Key features of the requirement is: Authoritative and ACL hierarchical access to repository
|
Git, combined with a "central" server managed withGitolite, can provide all the fine-grained control you need (per user/per group, with access to all or only some part of the repo, even to only some branches).
That being said, if your developers are more familiar with a CVCS like SVN, it might be wiser to use that kn... |
I'm looking for a way to easily debug C code in an Android NDK application using Eclipse. I've read ways to debug the app using gdb or something similar but what I want is a way to push messages to Eclipse somehow.
I'm looking for a solution that's as simple as using a print function in C and seeing it in the DDMS L... |
You can use the Android logging facilities:
```
#include <android/log.h>
#define APPNAME "MyApp"
__android_log_print(ANDROID_LOG_VERBOSE, APPNAME, "The value of 1 + 1 is %d", 1+1);
```
Make sure you also link against the logging library, in your Android.mk file:
```
LOCAL_LDLIBS := -llog
```
|
In the following code, is the behaviour undefined ?
```
#include<stdio.h>
int main()
{
printf(7+"%c","sundaram");
}
```
Its printing "aram". Can't understand how.
|
This is undefined behavior.
A string literal in C is a pointer to a a block of pre-initialized memory.By coincidence, your two string literals occupy adjacent blocks of memory.When you add7to the pointer to the first literal, you end up pointing into the middle of the next literal.
Your program's data is arranged in... |
I'm having trouble using bool as a type compiling with ndk-build:
```
bool test = true;
```
error:
48: error: 'bool' undeclared (first
use in this function)
Any ideas?
|
boolis not a built-in type in C. You need to#include <stdbool.h>to get it.
|
Does anyone know of any C parser library for .NET?
(I'm intending to parse C code into some form of object graph, so I can convert it to a different language.)
|
ANTLR can do what you'd like. It has a C preprocessor and ANSI C grammar.
https://github.com/antlr/grammars-v4
|
I'm looking for sample code on how to use the TMS3705 RFid transponder base station IC to communicate with the TMS37157 RFid device.
The TMS3705 datasheet is not very helpful - it only describes the physical interface.
Either sample code or a good description of how to construct/send a transmit packet and receive/par... |
The TMS3705 is used in thePaLFI Evaluation kit TMS37157. You find the reference to theFAQ.
|
I am currently looking into writing a plugin for mysql in C. I have been reading and studying MySQL 5.1 Plugin Development (http://www.amazon.com/MySQL-Plugin-Development-Sergei-Golubchik/dp/1849510601) which has been helping me out a lot. However I can't seem to find any examples that execute queries. I tried Googlin... |
I haven't used Mysql with C before, however you might want to take a look at these links:
http://dev.mysql.com/doc/refman/5.1/en/c-api-function-overview.htmlhttp://www.mysql.com/downloads/connector/c/
If you know MySql I think those links would be a good starting point at least.
|
Count amount of digits in a given number or input by the user.
|
Independent of programming language:
floor(log10(x))+1
where x is your number (>0).
If you want to handle 0 and negative numbers, I'd suggest something like this:
x == 0 ? 1 : floor(log10(abs(x)))+1
|
Can sombody explain how this works?
```
int x, y;
....
(some_condition ? x : y) = 100;
```
Is this intended to work or is is just a "blind" translation or the compiler (something likevec[10]equals10[vec])?
|
This is valid C++ and invalid C.
The result of a conditional expression can be (and in this case is) anlvaluein C++ refering to one ofxorydepending on whethersome_conditionevaluates totrue. In C++ eitherxis assigned the value 100 if some_condition istruewhen converted to abool, otherwiseyis assigned 100.
In C, the r... |
Could you please tell me the logic of usingsizeof data / sizeof *datainthis codeline 17?
```
...
unsigned char data[16];
...
size = fread(data, sizeof *data, sizeof data / sizeof *data, file);
...
```
Thanks
|
That's a common C idiom for "number of elements in an array".
Since an arraydecays to a pointerat the slightest provocation,*datais the first element of the array, and therefore it's dividing the total size of the array by the size of its first element, giving a count of elements.
There are any number of possible ob... |
Base on the answers i've got, i think this problem is kind of meaningless. Thanks for all your kind replies!
i want to get a binary number with its rightmost j bits set to 1 and others set to be 0. basically, there are two methods. i wanna know which of them is more efficient, or is there a more efficient way than th... |
Not sure if it's the answer you're looking for, but I'll bet it won't make more than a nanosecond of difference. :)
Or, to put it another way: Don't micro-optimize it unless that one-liner is the bottleneck in your code.
If you needotherforms of fast bit manipulation that might actually be slower, try looking at the... |
If I have several sets of numbers (just a 2D array where each row is a set):
```
[ 1, 3, -1, -1]
[ 2, 4, -1, -1]
[ 7, 8, 9, 10]
```
What would be an algorithm to create a list of sums (ignoring -1's)? the result for the above would be:
```
1+2+7,
1+2+8,
1+2+9,
1+2+10,
1+4+7,
1+4+8,
1+4+9,
1+4+10,
3+2+7,
3+2+8,
3+... |
For each number in the first list, generate all sums starting with that number and all sums recursively generated by applying the same method to all but the first list. When you have no lists left, that is the base case.
Pseudo-code:
```
function find_sums(lists):
if lists is empty:
return [""]
sums ... |
This question already has answers here:Closed12 years ago.
Possible Duplicate:Container Class / Library for C
I expect I'd be forced to use vectors, lists and sets for my C program. Should I invent those entities from scratch, or there is some kind of standard library for C as STL is for C++ ?
|
C doesn't have templates, so it might be difficult to implement those C++ collections in a generic way. I'm not aware of any libraries that implement those features in C.
If I were faced with such a situation, my first thought would be to isolate the parts
of my program that would benefit from C++ features, write t... |
I'm writing an app in C that requires MySQL interaction, so I downloaded the Connector/C archive from the official website, and it contains bin, lib and include folders, but I don't know where to install them.
I could copy the include files into my project folder, but where can I put the lib file so that my compiled b... |
This is confusing, isn't it.. don't know why they don't make this more clear.
The lib/ files go in /usr/local/lib
The include/ files go in /usr/local/include
The bin/ files go in /usr/local/bin
The /usr/.. directory isn't visible through finder afaik so you have to go at it via commandline. Best of luck
Also, in y... |
This is a tricky C question asked in interview: Write a program that does nothing, not even taking up memory.
Is it possible to do so?
|
All programs use memory. When you run the program, the OS will set up an address space for the program, copy its arguments into its process space, give it a process ID and a thread, give it some file descriptors for I/O, etc. Even if your program immediately terminates you still use up this memory and CPU time.
|
```
int myvar=100;
main()
{
pid_t (*f) (void );
int *ip;
int myvar=10;
f = (pid_t(*) (void)) dlsym(RTLD_NEXT, "getpid");
ip = (int *) dlsym(RTLD_NEXT, "errno");
if (ip)
printf("%d \r\n", *ip);
ip = (int *) dlsym(RTLD_NEXT, "myvar");
if (ip)
printf("%d \r\n", *ip); //not work where is i am ... |
Thegetpidanderrnosymbols are exported by the libc.myvvarsymbols is in your executable and is probably not exported.
Objdump -T will help you to check if the symbol is exported or not.
```
$ objdump -T /lib/libc.so.6 | grep -w getpid
00c9c570 g DF .text 00000036 GLIBC_2.0 getpid
```
|
Given
```
char foo[1024] = "bar";
```
This will initialize foo to contain 'b','a','r',0 . Is the remaining 1020 characters zero initialized, or uninitialized ?
I'd think the above is the same as `char foo[1024] = {'b','a','r','\0'} ; and as with initializing of aggregates, any member not mentioned is initialized to... |
If an array/aggregate is initialized somehow[edit: by use of a static initializer], the remaining unspecified entries are zeroed, yes.
|
I'm kind of new to C, but not to programming. I'm trying to create a program that takes an input and replies with a random string that's already saved in an array (for example).
I'm not trying to create a random string, I want them to be "fixed", like in Java:
```
String [] sa;
sa[0] = "Hello, World";
sa[1] = "Hi ... |
```
const char *sa[]={"Hello, World","Hi dude!"};
```
Then you can do
```
return sa[i];
```
The return value ischar *Just make sureiis within bounds
|
I want to create a tool like mini task manager. I want to show all the running processes, cpu and memory usage. Can anybody tell me related api's which I can use for this. Any link to related web page will be appreciated. (I want dump of all the statistics of running processes, cpu and memory.) Thanks in advance.
|
To do that, you will need touse the tool help functions to get snapshotsof the system.
Hereis a code example.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer... |
You may want to take a look atMemProf.
|
Is it this kind of thing:
```
for(;;)
{
statements;
}
```
Or is it this:
```
for(initialisation;condition;updation)
{
}
```
I am looking for answers with references to a variety of sources.
|
Your first case (forwith empty expressions) is aninfiniteloop and the second one (with empty body of theforstatement) is anemptyloop
|
I was wondering, do most implementations ofcalloctreat the size as an alignment too, and round it up to the next supported granularity?
If so, then do they round up to the next power of 2, or do they round to the next multiple of 8 or 16?
Ifcallockeeps the parameter the same, then how does that even work? Wouldn't y... |
sizeofis defined to yield the size of an object within an array -- in other words, it already accounts for any padding that's needed for proper alignment. So ifsizeof(foo)is 23 for some objectfoo, then your processor must be byte-aligned. (On the other hand, if you're passing 23 because you just think it's a good valu... |
```
TCHAR finalpath[MAX_PATH];
GetCurrentDirectory(MAX_PATH,finalpath);
TCHAR filename[] = TEXT("\\lista.txt");
wcscat(finalpath,filename);
wprintf(L"List will be saved to %s", finalpath);
```
So this basically confirms me that finalpath is indeed c:\somepath\lista.txt
but_wfreopen(TEXT(finalpath),TEXT("w"),stdout);... |
You don't use the TEXT macro with variables. I'm surprised that_wfreopen(TEXT(finalpath),TEXT("w"),stdout);even compiles.
Try_wfreopen(finalpath,TEXT("w"),stdout);
|
GCC has__builtin_prefetchto support prefetching. My question is how can I prefetch the data to a specific level of cache. For example, I only would like to prefetch the data toL2 cacheinstead of all the way toL1 cache.
|
__builtin_prefetchhas three arguments; the third one is the cache level. AFAICT, this has only effect on SSE, where it generates prefetchnta, prefetcht1, prefetcht2, prefetcht3, respectively.
|
I wrote a touchpad program in C that provide x,y information of the touchpad. Now, I want to transfer that X,Y values to a C# program. I tried to write the information to a file and read using C#. But, as C program blocked the text file, I was getting the following error:
The process cannot access the file 'C:\simple... |
I think what you are looking for is Interprocess Communication, IPC. There are many ways,thispage describes all the different ways on Windows and when to use which.
In my opinion I think you should consider usingData Copy.
|
I build the code, then when I try to run it, it executes and exits quickly .
I am pretty sure that there is a way in the project configuration , but I forgot how .
|
You can always just usegetc()before the return. Enter a character and it will exit..
Or run the VSctrl+f5combination, or add a breakpoint if debugging.
|
What is the use of padding struct in C?
|
Some architectures will perform better if only aligned accesses are made, so putting 32-bit objects on 32-bit boundaries, and 64-bit objects on 64-bit boundaries can improve the speed of your application.
Some architectures are completely incapable of making unaligned accesses, and on those architectures not padding ... |
Consider I have a struct:
```
struct SimpleStruct {
int x;
int y;
int z;
}
```
Now if I have 3 separate threads, each which only updates one of the x,y,z fields of the struct respectively, is it safe to let them update concurrently, or should I use a mutex or something to stop that from happening?
|
It is safe (structs are aligned).
However you should be careful about false sharing (seeHerb Sutter's articleabout it): if the fields are in the same cache line the writes will be effectively serialized.
|
Is there an API to get the number of CPUs available in Linux?
I mean, without using /proc/cpuinfo or any other sys-node file...
I've found this implementation using sched.h:
```
int GetCPUCount()
{
cpu_set_t cs;
CPU_ZERO(&cs);
sched_getaffinity(0, sizeof(cs), &cs);
int count = 0;
for (int i = 0; i < 64; i++)
... |
```
#include <unistd.h>
long number_of_processors = sysconf(_SC_NPROCESSORS_ONLN);
```
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:string to float conversion?
how can i convert a string to float in c with only Libc?
|
You can usestrtodorsscanfto do this.
|
Is there any other way to execute a program using kernel, other than shell and system calls?
|
It always used to be the case that there was really only one way to execute a program on Unix and its derivatives, and that was via theexec()system calls. The very first (kernel) process was created by the boot loader; all subsequent processes were created byfork()andexec(). Of course,fork()only created a copy of th... |
pxandpyare the x and y coordinates of a point on a circle's circumference.
Given:
```
the center of the circle as: cx, cy
the radius of the circle as: r
px
```
How to calculate the value ofpy? Thanks!
|
Given px there are at most two possible values for py.
Look at the pythagorean theorem: (px-cx)^2+(py-cy)^2=r^2.
Let d=r^2-(px-cx)^2
If d>0 then you have two solutions. This gives py=sqrt(d)+cy, where the square root is positive or negative.
If d=0 then you have one solution py=cy, the left or right of the circle,... |
Ok: I edited my question:I heard somewhere that php language is written in C.
So what happens for example when you run a function in php such asdate("Ymd");orfile_get_contents("file.txt");?
Does it translate that code to C and request to server, or does php do it?
And if it does translate it and request, that means... |
That is incorrect.
If you mean the language PHP is implemented in, it is C, not C++; see thePHP wikipedia page, under Implementation Language.
That does not, however, mean that it "translates" code to C; PHP is an interpreted language.
While executing code, it does of course have to use functions written in C, sinc... |
There is a sequence of increasing numbers that have the same number of binary 1s in them. Given n (the number of 1 bits set in each number in the series) write an algorithm or C program to find the n'th number in the series.
I found this question on internet and I think the answer is just (((1 << (n+1)) - 1) & ~2). I... |
(1 << n+1) - 3is a more concise way to express the result, but yes, I believe your expression is also correct.
|
My project right now works with XP and up, WINVER == 0x501 . However, for those using Vista and up, I would like to do:
```
case WM_MOUSEHWHEEL:
```
in my WNDPROC
However when I try to build that I get undeclared identifier WM_MOUSEHWHEEL
is there a way to maintain compatibility with XP, but to let Vista & 7 users... |
Use this:
```
#ifndef WM_MOUSEHWHEEL
#define WM_MOUSEHWHEEL 0x020E
#endif
```
There, that should be correct
NOTE: I originally answered WM_MOUSEWHEEL, not WM_MOUSEHWHEEL. Correct. :P
|
I'm working on a fun project where I need a simple key/value store that uses B+Trees. I studied them some years ago, and to be honest, I don't want to reinvent the wheel, so I'm looking for a simple implementation in C of b+tree that I can just include in my project.
I know of sqlite's, dbm's and tokyocabinet's ones ... |
There's one listed in thewikipediaarticle:
Interactive B+ Tree Implementation in C
Perhaps you can edit out the "interactive" parts?
|
Given
```
char foo[1024] = "bar";
```
This will initialize foo to contain 'b','a','r',0 . Is the remaining 1020 characters zero initialized, or uninitialized ?
I'd think the above is the same as `char foo[1024] = {'b','a','r','\0'} ; and as with initializing of aggregates, any member not mentioned is initialized to... |
If an array/aggregate is initialized somehow[edit: by use of a static initializer], the remaining unspecified entries are zeroed, yes.
|
I'm kind of new to C, but not to programming. I'm trying to create a program that takes an input and replies with a random string that's already saved in an array (for example).
I'm not trying to create a random string, I want them to be "fixed", like in Java:
```
String [] sa;
sa[0] = "Hello, World";
sa[1] = "Hi ... |
```
const char *sa[]={"Hello, World","Hi dude!"};
```
Then you can do
```
return sa[i];
```
The return value ischar *Just make sureiis within bounds
|
I want to create a tool like mini task manager. I want to show all the running processes, cpu and memory usage. Can anybody tell me related api's which I can use for this. Any link to related web page will be appreciated. (I want dump of all the statistics of running processes, cpu and memory.) Thanks in advance.
|
To do that, you will need touse the tool help functions to get snapshotsof the system.
Hereis a code example.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer... |
You may want to take a look atMemProf.
|
Is there an API to get the number of CPUs available in Linux?
I mean, without using /proc/cpuinfo or any other sys-node file...
I've found this implementation using sched.h:
```
int GetCPUCount()
{
cpu_set_t cs;
CPU_ZERO(&cs);
sched_getaffinity(0, sizeof(cs), &cs);
int count = 0;
for (int i = 0; i < 64; i++)
... |
```
#include <unistd.h>
long number_of_processors = sysconf(_SC_NPROCESSORS_ONLN);
```
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:string to float conversion?
how can i convert a string to float in c with only Libc?
|
You can usestrtodorsscanfto do this.
|
I'm looking for a simple C Wrapper of zlib, to decompress a byte array. Anyone knows one ?
|
By wrapper function, you probably mean some simpler to use, more self-contained functions?
Zlib contains them. Have a look in themanualunder "Utility Functions".
You're probably look for:
ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
const Bytef *source, uLong s... |
I am having trouble getting to grips with the definition and uses of symbolic and literal constants and I was wondering if you anyone could explain them and highlight their differences. Thanks!
|
A literal constant is a value typed directly into your program wherever it is needed. For example
int tempInt = 10;
tempInt is a variable of type int; 10 is a literal constant. You can't assign a value to 10, and its value can't be changed. A symbolic constant is a constant that is represented by a name, just as a v... |
I'm trying to figure out how to detect whether a binary has been compressed with UPX. I am using a simple CRC to detect whether my app was in any way changed and if the CRC failed on the size due to a packer I would like to detect that as OK.
Right now I am starting with UPX.
So, is there any marker on the binary? a... |
Downloadupxsource code fromUPX Homepageand opensrc/p_w32pe.cppfile; the function you are looking for is;
```
int PackW32Pe::canUnpack()
```
This function checks if the file is compressed with win32 upx.
|
How do I send UDP packet from aspecificinterface on Linux using C? Should I use bind? Is it possible to send UDP from the interface not having IP address?
Thanks.
|
Use bind. You cannot send UDP packets via an interface that does not have an IP address, because UDP uses the Internet Protocol and the Internet Protocol requires an IP address.
|
I have this simple code:
```
int main()
{
float x = foo();
printf("returned value: %f", x);
return 0;
}
float foo ()
{
return 5;
}
```
when i run the code , the output is:"returned value: -858993472.000000"
can somebody please explaing to me why does the returned value isnt 5.000000?
|
At the point at which you call the function there is no prototype in scope. This means that the function is assumed to returnint. Add a prototype before the point where you first call the function.
```
float f(void);
```
|
When debugging a program which uses (either C or C++),gdbdisplays complex numbers as_M_value = xxx + yyy*I(with a type ofcomplex double).
While debugging, I need to print that number multiplied by a factor.
The followingdoes notwork:
```
print a * 8.0
```
I getArgument to arithmetic operation not a number or boo... |
If you use the standard C++ complex template then complex::real() and complex::imaj() should work.
my2c
Note : Was a comment ^^
|
I'm writing a C/CGI web application. Is there a library to parse a query string into something like aGHashTable? I could write my own but it certainly doesn't seem to be worth the effort to reinvent the wheel.
|
Theuriparserlibrary can parsequery stringsinto key-value pairs.
|
I have a time stored in a 64 bit int of the form 20110103101419 (i.e. representing 2011-01-03 10:14:19). How do I convert that to seconds since 1970 ?
|
My C is a bit rusty, but looking at the other two answers I would write a function as follows, returning the number of seconds since epoch or -1 in case of error.
```
#include <stdio.h>
#include <time.h>
time_t convertDecimalTime(long dt) {
struct tm time_str;
time_str.tm_isdst = -1;
time_str.tm_sec = dt%10... |
I want to learn C/C++ GUI Windows/Linux programming. Which IDE is more suitable? If I go with Visual Studio.NET, what are the pros and cons of it.
Any IDE that supports both Windows and Linux?
|
TheQt Creator IDEworks for both Linux and Windows.
If you want a more versatile development environment, Qt can integrate with Eclipse.
|
I need to store exactly four booleans in my struct in c. Yes I could use four integers or put them into an array but I would like to do it a bit nicer. I was thinking about an int like "0000" where each number would represent the boolean value, but then when editing I cant edit only the one digit, right? That doesnt l... |
You could use a bitfield struct:
```
struct foo {
unsigned boolean1 : 1;
unsigned boolean2 : 1;
unsigned boolean3 : 1;
unsigned boolean4 : 1;
};
```
You can then easily edit each boolean value separately, for example:
```
struct foo example;
example.boolean1 = 1;
example.boolean2 = 0;
```
|
I wonder if there is a software that can help us determine all possible origins of a function call.
For example:
```
/* in file f1.c */
int f1() {
x_func();
}
/* in file f2.c */
int f2() {
x_func();
}
```
If we want to trace the origin of all function calls to x_func(), the output will be:
```
f1.c:f1()
f2.c:f2... |
cscopecan help here
|
In ruby there's very common idiom to check if current file is "main" file:
```
if __FILE__ == $0
# do something here (usually run unit tests)
end
```
I'd like to do something similar inCafter reading gcc documentation I've figured that it should work like this:
```
#if __FILE__ == __BASE_FILE__
// Do stuf... |
in gcc you can use:
#if __INCLUDE_LEVEL__ == 0
or:
if(!__INCLUDE_LEVEL__)
to check if your inside the __BASE_FILE__
|
In .NET land, there's the tremendously usefulSystem.Windows.Forms.CheckedListBoxclass.
What is the equivalent in Windows Common Controls land? (if any)
|
Turn a list view into one with checkboxes. If you want it similar to a ListBox, only use 1 column.
```
ListView_SetExtendedListViewStyle (handle, LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT);
```
|
When you download PHP's source you realize that all the goodies are in theext/directory in their respectivearray.c,string.c, etc. files.
Now, I was wondering, it is possible to call these functions from a C program having those PHP C files?
|
You can do it but that doesn't mean it's a good idea. The PHP library functions deal with PHP's internal data types, memory allocation and management schemes, etc. You'd probably end up wasting a lot of time and effort on marshalling data between PHP and C.
Most of the functionality is probably available in C librari... |
Greetings,
I'm working on alow levelprogramming project and I want to play a music with the computerspeaker.
I'm already capable of using the speaker (withtimer2) and a song is represented in the following way:
```
note_t *music;
```
wherenote_trepresents a note and it's compound by:
```
typedef struct {
int fr... |
Depending on your exact purpose, you can use one of the ringtone formats or invent your own.
An example simple ringtone format isRTTTL.
|
How many times 'x' value will betestedin the following code snippet ?
```
int x;
for(x=0;x < 10; x++)
printf("%d",x);
```
To me it seems that the answer is11but my module says it is10?! what am I missing?
|
Eleven, as the condition is tested at thebeginningof each loop iteration, before printf is called:
```
0 < 10 == true
1 < 10 == true
2 < 10 == true
3 < 10 == true
4 < 10 == true
5 < 10 == true
6 < 10 == true
7 < 10 == true
8 < 10 == true
9 < 10 == true
10 < 10 == false // exit from loop (printf not executed)
```
|
Is there a specific reason to use ldiv or div instead of '/' or '%' to divide/modulus two variables?
|
Yes. C99 §7.20.6.2/2 says:
Thediv,ldiv, andlldiv, functions computenumer / denomandnumer %
denomin a single operation.
|
I learnedenumswhen I learned C and from time to time I keep myself reminding about it and most of the time by re-reading from some source,it occurred to me that this is due to the fact I never use it in my programming,my programming interest concentrate around algorithmic problem solving so I am not sure where could ... |
Imagine that you are programming a depth first search and you want to tag your edges with whether they are tree, back, forward, or cross. You could create an enum EDGE_TYPE with the four possibilities and use it to tag your edges.
|
I have doubts about many things related with the different C specifications.
If I program a library in C99, can I use it from C89 code? (using only the functions with C89 compliant definitions).
example, this code would be usable in C89?
Header of a shared library:
```
#ifdef C99
void func (double complex a, doub... |
The C language does not say anything about binary compatibility of C89 and C99 code. That is entirely up to the compilers you use for the different parts of the executable.
If you can make the external headers of your library palatable for a C89 compiler, I don't see any obvious reason why it would not work, except f... |
C history question here. Why does the C functionputcrequire a second parameter like
```
putc( 'c', stdout ) ;
```
While puts is oh so more convenient
```
puts( "a string" ) ;
```
There is a function in msvc++
```
putchar( 'c' ) ;
```
Which works the way one might expectputcto work. I thought the second paramet... |
```
int putc ( int character, FILE * stream );
```
Writes a character to the stream and advances the position indicator.So it is a more generic function thanputcharOther functions can be based on this e.g.
```
#define putchar(c) putc((c),stdout)
```
According to Kernighan's bookputcis equivalent withfputcbutputccou... |
in Linux playing or recording some audio is just read or write /dev/dsp But how to do the same in windows ? (with C)
|
There is no static device name, you should usewaveOut*functions,hereis a nice example of using those APIs.
|
I am writing C89, C90, Ansi-C Code. One of my functions requires a struct as a parameter. I want to call the function with the initialization of that struct rather than creating a struct first then passing it to the function.
Here are some snippets which work.
```
typedef struct {
char* EventName;
char* Mess... |
Use the compound literal(Event){"infomessage", "Testmessage"}, ie
```
Notify((Event){"infomessage", "Testmessage"});
```
|
I'm having a trouble in opening FIFOs in C.. first I created them using mkfifo() function with permission : 0777, and when I tried to open them, it succeeded in opening the first FIFO only, then the process will stuck in opening the second FIFO, and this is my code :
```
fd1 = open("FIFO1_PATH", O_WRONLY );
fd2 = ope... |
I just got it right :)
I have to let the opening process wait until some other process opens the FIFO for reading (and it will be a blocked reading).. by doing sleep on the writing process I will ensure that the other process will opens for reading ..
|
I'm trying to find all subfolders in a file's path that have 'others exec' permission.
I've tried to usestrtok(path_str,"/")to break the path string, but when usingstat()for the sub-directories of the root of the process I run, I get the "not a file or folder" error.
Any suggestions on how I can overcome this error?... |
If the path is"long/path/to/the/file.txt", then you will need to callstat()on"long","long/path","long/path/to"and"long/path/to/the". If you don't care in what order you check these, the easiest way is probably to repeatedly usestrrchr():
```
char *s;
while (s = strrchr(path, '/'))
{
*s = 0;
if (strlen(path)... |
I want to define a function in C language which can take an unlimited number of arguments of any datatype.
For example:printf(),scanf(), etc.
Any idea on this?
|
To use variable number of arguments in C you need to include the header
```
#include <stdarg.h>
```
printf()in C is an example of function that takes variable number of arguments.
```
int printf(const char *fmt, ...)
```
More infohere
|
How can i get the last digit of an integer (or NSInteger) outputted to integer?
example:
```
int time = CFAbsoluteGetCurrent();
int lastDigit;
```
|
Usemodulo:
```
int lastDigit = time % 10;
```
|
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... |
If you mean systems level then perhapsD Language.
|
```
char program[3] = { 0x6a, 0x0a, 0xC3 }; //push 10; ret;
char (*p)(void) = program;
printf("char = %c \n", p());
```
This code crashes. Why?
The following code works ok:
```
char program[3] = { 0x90, 0x90, 0xC3 }; //nop; nop; ret
void (*p)(void) = program;
p();
```
|
Because you need to cleanup your stack by popping from it. Read more on theretinstruction - it will load cs:ip with values from the stack!
|
I have a text file and would like to check if it contains a string.
The text file is stored in a char array:char buffer[512][128];.
Q1: Is it easier if I buffer it in one long array instead of a multidimensional array?
Q2: How could I check whether the buffer contains the stringchar *s1 = "Hello world!";?
I will ... |
It will be much easier to use a single 1D array.strstr(buffer, s1)!= null(once you've changedbufferinto a 1D array)
|
the problem is i dunno how long the string will be, so i dunno how much should i allocate for my data...
```
char *Data = malloc(1024*1024); //???????
sprintf(Data, "%s %s", Data1, Data2);
```
Data1 and Data2 varies in Size from time to time.... from very very long to very small
i was wondering if there is away to ... |
Many C runtime libraries (for instance, GNU's glibc and FreeBSD's (and NetBSD's and OpenBSD's and OS X's) libc) provideasprintf, which combinesmallocandsprintfinto a single call.
```
char *Data = NULL;
asprintf(&data, "%s %s", Data1, Data2);
```
Assuming the return value indicates success, enough space has been dyna... |
Why condition rand() % 3 is true approximatelу EVERY 3 time ? rand is REALY random isn't it ?
|
You realize, of course, that even a fair coin can give you ten heads in a row. There's a probability that can be assigned to that combination.
A fair coin will give half heads and half tails overmanytrials, but it's not guaranteed to be 50/50 over a shorter run.
Your own experience of the physical world tells you t... |
can any one provide me a link for B-tree code in C,have understood the algorithm but still have problems in coding it
|
c++http://touc.org/btree.html
c (slightly fancier than normal)http://code.google.com/p/high-concurrency-btree/downloads/list
|
In .NET land, there's the tremendously usefulSystem.Windows.Forms.CheckedListBoxclass.
What is the equivalent in Windows Common Controls land? (if any)
|
Turn a list view into one with checkboxes. If you want it similar to a ListBox, only use 1 column.
```
ListView_SetExtendedListViewStyle (handle, LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT);
```
|
When you download PHP's source you realize that all the goodies are in theext/directory in their respectivearray.c,string.c, etc. files.
Now, I was wondering, it is possible to call these functions from a C program having those PHP C files?
|
You can do it but that doesn't mean it's a good idea. The PHP library functions deal with PHP's internal data types, memory allocation and management schemes, etc. You'd probably end up wasting a lot of time and effort on marshalling data between PHP and C.
Most of the functionality is probably available in C librari... |
Greetings,
I'm working on alow levelprogramming project and I want to play a music with the computerspeaker.
I'm already capable of using the speaker (withtimer2) and a song is represented in the following way:
```
note_t *music;
```
wherenote_trepresents a note and it's compound by:
```
typedef struct {
int fr... |
Depending on your exact purpose, you can use one of the ringtone formats or invent your own.
An example simple ringtone format isRTTTL.
|
How many times 'x' value will betestedin the following code snippet ?
```
int x;
for(x=0;x < 10; x++)
printf("%d",x);
```
To me it seems that the answer is11but my module says it is10?! what am I missing?
|
Eleven, as the condition is tested at thebeginningof each loop iteration, before printf is called:
```
0 < 10 == true
1 < 10 == true
2 < 10 == true
3 < 10 == true
4 < 10 == true
5 < 10 == true
6 < 10 == true
7 < 10 == true
8 < 10 == true
9 < 10 == true
10 < 10 == false // exit from loop (printf not executed)
```
|
Is there a specific reason to use ldiv or div instead of '/' or '%' to divide/modulus two variables?
|
Yes. C99 §7.20.6.2/2 says:
Thediv,ldiv, andlldiv, functions computenumer / denomandnumer %
denomin a single operation.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.