question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
Since a function in C returns only one value, all the time, how canfork(), which is also a function, return two values?
|
The fork function returns 0 to the child process that was created and returns the childs ID to the parent process.
The two seperate processes are each returned a single value.
So think of it more as one return being called on eachthreadprocess.
|
How do you set optimization/debugging flags in Eclipse CDT, set up uses GNU tool-chain ??
Thanks !
|
You can also go to Project Properties -> C/C++ Build -> Settings -> Tool Settings. Click on the triangle next to your compiler to see the drop down menu -> click on Optimization. On the right hand side next to Optimization Level choose from the drop down menu your desired level. (Be aware though that once you set opti... |
Just wondering, is the GNU C Library (glibc) usable on non-GNU and/or non-POSIX platforms such as Microsoft Windows?
|
Yes, its possible in theory, but not really worth it in practice. You would need to port the syscall interface, dynamic linker, and other parts to Windows or your platform of choice, and Glibc is not an ideal candidate for this.
If you really need a self contained C library, I would considernewliboruClibc(or FreeBSD'... |
in unistd.h
using open() with the O_APPEND flag gives atomic writes always to the end of the file...
this is great and all, but what if i need to know the offset at which it atomically appended to the file...?
i realize O_APPEND is often used for log files, but I'd actually like to know at what offset in the file i... |
To get the current position in a file descriptor, uselseek()with offset0and whenceSEEK_CUR.
```
int fd = open(...);
if (fd) {
off_t positionWhereAppendingBegins = lseek(fd, 0, SEEK_CUR);
write(...);
close(fd);
}
```
Note that this will not give you reliable results if the descriptor was opened some other... |
How do you convert a favicon.ico to a regular web-accessible graphics - gif, png, or jpg using PHP or C/C++/CGI?
Are there methods that do not require ImageMagick?
|
You cold useimagemagick. Eigther you usethe native php extensionor you use a phpexeccommand (for a commandline command) and then get the transformed image or as last option you use imagemagick as a server and request the new image from a webadress.
There are other commandline tools available, but they are not as powe... |
Why don't any programming language load the default libraries likestdio.h,iostream.horusing Systemso that there declaration is avoided?
As these namespace/libraries are required in any program, why the compilers expect it to be declared by the user.
Do any programs exist without using namespace/headers? even if yes,... |
It's because thereareprograms which are written without the standard libraries. For example, there are plenty of C programs running on embedded systems that don't providestdio.h, since it doesn't make any sense on those platforms (in C, such environments are referred to as "freestanding", as opposed to the more usual... |
I require some informations like the amount of resend packages/packet-loss occurred for a specific TCP-Socket I created. Does somebody know a way how to access or request such informations directly from my C/C++ program? Maybe something Linux specific?
Or do I need (as a workaround) to capture and analyze my own traf... |
By usinggetsockopt()to get orsetsockopt()to set TCP socket options, you can useTCP_INFOoption on linux machines in order to get information about a socket. This option should be avoided if you want the code to be portable.
What you will get back is astruct tcp_infofrom the kernel that contains information such as ret... |
I have looked at how to generate two random ints with rand()%n (where n is the total number of samples) but they seem to usually have a bias.
Is there a better (and preferably simpler) way to generate random numbers between 0 and n (number of samples)?
n is read from a file which contains a list of data points. The ... |
rand() % nuses only the low bits of the random number whennis significantly smaller thanRAND_MAX. It's better to use all of the bits e.g. by dividing byRAND_MAXto get a (floating point) number between 0.0 and 1.0 and then multiplying bynand converting back to an integer.
It is also possible that the implementation of... |
This question already has answers here:Placement of the asterisk in pointer declarations(15 answers)Difference between int* p and int *p declaration [duplicate](3 answers)difference between int* i and int *i(9 answers)Closed4 years ago.
What is the most proper way to place asterisk? Why?
```
1) type* var;
2) ... |
It does not matter as far as you are declaring only one pointer. It is usually writen like in the second example (in the code I usually read/write) but for the compiler it's the same.
The trouble can come out if you are declaring more than one pointer. For example, this is not declaring two pointer, instead it declar... |
I am trying to copy the memory value of int into the char buffer. The code looks like below,
```
#define CPYINT(a, b) memcpy(a, &b, 4)
............
char str1[4];
int i = 1;
CPYINT(str1, i);
printf("%s",s);
...........
```
When I print str1 it’s blank. Please clarify.
|
You are copying the byte representation of an integer into a char array. You then askprintfto interpret this array as a null terminating string :str1[0]being zero, you are essentially printing an empty string (I'm skipping theendiannesstalk here).
What did you expect ? Obviously, if you wanted to print a textual repr... |
I'm very new to dealing with bits and have got stuck on the following warning when compiling:
7: warning: left shift count >= width of type
My line 7 looks like this
```
unsigned long int x = 1 << 32;
```
This would make sense if the size oflongon my system was 32 bits. However,sizeof(long)returns8andCHAR_BITis de... |
longmay be a 64-bit type, but1is still anint. You need to make1along intusing theLsuffix:
```
unsigned long x = 1UL << 32;
```
(You should also make itunsignedusing theUsuffix as I've shown, to avoid the issues of left shifting a signed integer. There's no problem when alongis 64 bits wide and you shift by 32 bits... |
I am currently trying to use Eclipse to develop some code that I've been doing in a text editor in C.
I am currently under Linux, compiling it with GCC with the following arguments:
```
gcc -o SO SO.c -lpthread -lrt
```
I've tried adding"-lpthread -lrt"to Eclipse's "C/C++ Build"->"Discovery Options"-> "Compiler Inv... |
In the project properties, go to : C/C++ Build --> Settings.Then "Tool Settings", select "Libraries" under "Linker".You can add all your project libraries there (without the "-l"). Also in the lower part, you can add custom path to search libraries.
|
I have two windows console applications that I have written in C.
I don't have the source code for either of them.
I want to produce a single .exe file that runs both.
What are my options?
What if the second application is .Net code instead of C? Do I need to take special steps to load the .Net runtimes?
I am awa... |
I'd just go the simple way, store both exe's as resources or as binary arrays(seebin2c), write them out as temp files at run time, then execute them(either throughCreateProcess,spawnor via asystemcommand).
The other way would be to write your own variants or reverse engineer the ones you have(just make sure to keep i... |
I want to know the status of a process. I think I can use the wait family functions but actually I don't want to wait for the process, just check the status and go on.
I would want something like
```
checkStatusOfProcess(&status);
if(status == WORKING) {
//do something
} else if(status == exited) {
//do some... |
Then you want to use thewaitpidfunction with theWNOHANGoption:
```
#include <sys/types.h>
#include <sys/wait.h>
int status;
pid_t return_pid = waitpid(process_id, &status, WNOHANG); /* WNOHANG def'd in wait.h */
if (return_pid == -1) {
/* error */
} else if (return_pid == 0) {
/* child is still running */
} ... |
Why can you kind of cheat compiler this way:
```
const int a = 5;
*((int*)&a)=5; // VC/armcc does not complain
```
when above is "abridged" equivalent of this:
```
const int *ptr2const = &a;
int *ptr = ptr2const; // as expected error is raised here
*ptr = 5;
```
|
Casting is your way of telling the compiler "I know what I'm doing", so it doesn't complain. Unfortunately, in this instance, you will invoke undefined behaviour.
|
So I have this board, to play a boardgame... The problem is, how do I know in which square did the user click on? I know the x and y coordinates, but how do I automate it, without the need to hunt down the specific locations of each square. (Also the size of the board is variable...so it can have lots of squares, or v... |
There are a lot of options offered at:http://www.opengl.org/resources/faq/technical/selection.htm
|
i am trying to write udp chat server in c language. i have written tcp chat server before and it is ok.
in tcp server, accept function returns an fd number and server communicate with a specific client according to this fd number.
but in udp, how can i listen a specific client?
In my tcp server, after a client conn... |
You userecvfromto find out the source IP/port and then reply withsendto. You only need tobindto select a server port. You don'taccept. Allconnectdoes for UDP is set the default destination (which you plan to override withsendto).
|
What's going on here:
```
printf("result = %d\n", 1);
printf("result = %f\n", 1);
```
outputs:
```
result = 1
result = 0.000000
```
If I ensure the type of these variables before trying to print them, it works fine of course. Why is the second print statement not getting implicitly converted to 1.00000?
|
In the second case you have a mismatch between your format string and the argument type - the result is therefore undefined behavio(u)r.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:Reason for the Output
Hi,
Can you please explain me the output of this code snippet? The answer is "d"
```
void main()
{
short int a=5;
clrscr();
printf("%d"+1,a);
getch();
}
```
Thanks.
|
"%d" + 1is a pointer to"d", so in fact you are executingprintf( "d", a );.
|
In C/C++, the main function receives parameters which are of typechar*.
```
int main(int argc, char* argv[]){
return 0;
}
```
argvis an array ofchar*, and points to strings. Where are these string located? Are they on the heap, stack, or somewhere else?
|
They are compiler magic, and implementation-dependent.
|
I have a struct like this:
```
struct A
{
char x[];
};
```
What does it mean? When I do something like:
```
A a;
a.x = "hello";
```
gcc throws an error saying:
```
error: incompatible types in assignent of 'const char [6]' to 'char [0u]'
```
|
This is a C99 "flexible array member".
See here for gcc specifics:http://www.delorie.com/gnu/docs/gcc/gcc_42.html
|
I want to create a bidimensional array that represents the positions of a board game. I've defined that each position is of type 'struct position' which is a enum that can be 'empty', 'piece1' or 'piece2'. The problem is that the user decides which size the table is, that is, how many positions the bidimensional array... |
No, you can't define the size of an array at run-time in C. But one-dimensional arrays have the same semantics as pointers, so you can "emulate" a multi-dimensional by using pointers instead. Something like this should do the trick:
```
int w = 16, h = 16;
int *array = malloc(sizeof(int) * w * h);
int x = 4, y = 2;
... |
I'm planning out a science project, and I'm doing some research about sockets in various languages. Strangely enough, I cannot find whether C has sockets as part of some internal resource, or if the language requires an external library to use sockets. From what I've seen, I'm inclined to think that it is part of an i... |
Sockets are specified by POSIX but not C by itself. Basically any modern operating system you're likely to encounterexcept Windowsis approximately POSIX-conformant. On Windows, theWINSOCKlibrary provides a very poor substitute for standard POSIX sockets.
|
What are the Compiler Options & Other mechanism for reducing the static library size?
OS : VxWorks
Compiler : GCC
Language : C
|
Use-Osto optimise for smaller code size, and leave out-gand any other debug options.
|
This is a simplified version of my code:
```
void calc(char *s)
{
int t = 0;
while (*s)
{
if (isdigit(*s))
t += *s - '0';
else
++s;
}
printf("t = %d\n", t);
}
int main(int argc, char* argv[])
{
calc("8+9-10+11");
return 0;
}
```
The problem is with... |
sis not incremented if*sis a digit, consider removing the else clause, making the code into this:
```
while (*s)
{
if (isdigit(*s))
t += *s - '0';
++s;
}
```
|
```
while ((1U << i) < nSize) {
i++;
}
```
Any particular reason to use1Uinstead of1?
|
On most compliers, both will give a result with the same representation. However, according to the C specification, the result of a bit shift operation on a signed argument gives implementation-defined results, so intheory1U << iis more portable than1 << i. In practice all C compilers you'll ever encounter treat sig... |
How does one check if no connection is possible (that is, server is down...) with c sockets?
In other words; client tries to establish contact with a
connect(sock, (struct sockaddr *)&serveraddr, sizeof serveraddr), but server isn't responding.
Client should then get hold of some variable that could verify server sta... |
connect(3)will return -1 on error, and set errno to an appropriate error.
One case that you may have to handle manually is a timeout. For that, you can either use multiple threads (a second thread kills the socket if it's not connected after the timeout expires), or use non-blocking sockets +poll(2). But that should ... |
I have written down a code that should do garbage collection for c programs. The problem is that I need to run it for a large number of objects say 100 mb dynamically allocated.
Is there any tool that can help me find out the memory usage of my c code at runtime. It would be pretty helpful if I can come to know the c... |
Typically you can achieve this through use of your own object allocator quite easily. When you couple it into your garbage collection library, you can ensure that all GC'd objects use this allocator, so you don't miss anything. Anything not explicitly allocated by this allocator, is not garbage collected.
|
I'm trying to monitor the mouse position on client area of window. for example:
```
WM_MOUSEMOVE:
{
std::ostringstring oss;
xPos = LOWORD(lParam);
yPos = HIWORD(lParam);
oss << xPos << ", " << yPos;
TextOut(hDC, 100, 100, oss.str().c_str(), oss.str().size());
}
```
Do i need to measure the height, ... |
Every time you draw some text, useGetTextExtentPoint32to measure the size of the area written, and save that somewhere. Then when you try to draw something new, you can pass a rectangle based on that value into InvalidateRect to indicate your desire to erase, then UpdateWindow to make the erasure happen immediately.
|
I want to declare a string that will hold 4 chars
```
char st[4];
memcpy(st,"test",4);
```
but when I print st ... I have "test" and some other symbols printed after it - what is wrong in that ?
Thanks a lot
|
C strings, like the"test"string literal, are NUL-terminated, meaning the last character is '\0':
```
{'t', 'e', 's', 't', '\0'}
```
You would need to usest[5], and copy 5 characters, to have room for (and include) the NUL. As is, you're not including it in the copy. So aftewards,stlooks like:
```
{'t', 'e', 's', ... |
I have a c# application that is using a custom DLL (written in C, built with CL).
the DLL has many printf's that I'd like to be able to view while running my c# app. So far I havnt been able to figure out how to view the output from the DLL in visual studio (2010 or 2005).
I have a test app in C that runs the dll fr... |
You might consider the free utility from Sysinternals called DebugView:
http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx
I'm not sure if this will exactly solve your problem but if the calls are going through the right place you might be able to pick them up. It can't hurt to try.
|
I have a small C program calling a shell script myScript.sh. I am getting the value of ret as 256. Please help me in knowing what went wrong with the system call?
```
int main()
{
int ret;
ret = system (myScript.sh);
ret >>= ret;
if (ret != 0)
{
printf("ret is [%d]",ret);
}
}
```
Working on 64 bit UNIX operating ... |
On my system,man systemsays:
The system() function returns the exit status of the shell as returned by
waitpid(2), or -1 if an error occurred when invoking fork(2) or
waitpid(2). A return value of 127 means the execution of the shell
failed.
Thewaitpidman page describes a set of macros such asWEXITSTATUS()that e... |
I want to trace each path of function calls.
For eg:
```
int a()
{
b();
return 1;
}
void b()
{
}
int main()
{
int x=a();
return 0;
}
```
So my call trace is main->a->b
In this manner I want to trace each set paths of calls.
I have thought of a depth first search. But i am not sure how this would go.... |
There are a number of free call-graph programs listed in thisarticle, includingegyptwhich is a small Perl script that uses gcc and Graphviz to generate the static call graph of a C program.
|
i'm doing some code now and got some problem using restrict keyword.
```
typedef int* pt;
int foo(pt a, pt b)
{
... /* stuff */
}
```
What if I want to make a and b restricted? The code below failed:
```
typedef int* pt;
int foo(pt restrict a, pt restrict b)
{
... /* stuff */
}
```
Thanks in advance.
|
Make sure you're compiling it using the C99 flag for your compiler. Therestrictkeyword doesn't exist in C89 C.
|
Does anyone know a function/library that I could use to do general FTP functions in a FTP connection?
I'd rather have these in C, as that would be extremely easy to add to my current project.
|
libcurlis probably the best library you can use for that.
|
Why does the following bit of code work in C:
```
int res = pow(2, 3);
printf("%d\n", res);
```
while this other doesn't?
```
int a = 2;
int b = 3;
int res = pow(a, b);
printf("%d\n", res);
```
Even if I try
```
double a = 2;
double b = 3;
double res = pow(a, b);
printf("%f\n", res);
```
I get an
undefined re... |
When it works, it's because the calculation was done by the compiler itself (and included in the binary as if you wrote it out)
```
printf("8\n");
```
When it doesn't work, is because thepowfunction is included in the math library and the math library isn't linked with your binary by default.To get the math library ... |
What is a good bit-twiddling routine to convert a number in the range [2^N,2^(N-1)-1] to N?
Some examples:
f(1) -> 0f([2-3]) -> 1f([4-7]) -> 2f([8-15]) -> 3
Here is one implementation:
```
uint f(uint num)
{
for (uint shifts = 0; num; shifts++)
num >>= 1;
return (shifts - 1);
}
```
|
Depending on how wide your data-type is, and how much memory you have available, a lookup-table is one possibility. It's almost certainly the fastest approach.
For other approaches, seehttp://www-graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious, and the subsequent sections.
|
i will create a program check stock with barcode and database
what do i need to learn
What language should I use to development. And Should I use a database where.
c/c++, java, Visual C# not experience but pretty
spec
check in, check out and check amount in stock
Thank
sorry for grammar
|
Any of those languages will work. Most Barcode scanners are serial (RS-232), so you need to have the ability to connect through your language. I would suggest C# on a windows platform because the .NET platform has a well-defined serial port. Also, GUIs are pretty easy to implement.
As far as a database, you could s... |
Does anyone know a way to programmatically retrieve the ram memory manufacturer?
Thanks!
|
Modern RAM chips have an additional EPROM on board that contains a lot of information about the RAM. The standard for this is SPD, or Serial Presence Detect. At least some versions of SPD include a JDEC manufacturer's code.
Look atthis articlefor some introductory information on SPD. Not every RAM chip has the inform... |
i want to add some informations to a file in C under linux, can i save that information in its notes tab using C ?
Thanks a lot
|
I believe you want to set the attributes of a file (file properties that gets displayed when you see file properties from a GUI shell) from your C code. You may want to check out*xattrsyscalls:http://www.kernel.org/doc/man-pages/online/pages/man2/listxattr.2.htmlhttp://www.kernel.org/doc/man-pages/online/pages/man2/ge... |
I'm trying to create a downloader/update tool for my C application.
My updater PDL:
Download update.xml from webserverCheck update version by using fscanf and storing floating point to a variableCheck variable with an if statement if the version is greater than release version defined in applicationDownload update i... |
cURL (libcurl) would be the easy option:Download file using libcurl in C/C++Downloading all files in directory using libcurlhttp://curl.haxx.se/If your software is based on Microsoft Windows, then you can also use Wininet APIs:http://msdn.microsoft.com/en-us/library/aa385473.aspx
|
This code gives me warnings:
```
$ cat test.c
#include<stdio.h>
#include<time.h>
int main() {
time_t t;
scanf("%lld", &t);
printf("%lld\n", t);
return 0;
}
$ gcc test.c -o test
test.c: In function ‘main’:
test.c:7: warning: format ‘%lld’ expects type ‘long long int *’, but argument 2 has type ‘time_... |
The exact type oftime_tdepends on your platform and OS. It's still quite often 32 bit (eitherintorlong), not 64, and some even use floats. The correct thing to do is to read into a known-size integer (eitherintorlong long) and then assign the value to atime_tas a second step.
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
What do thedup()anddup2()system cal... |
Both make a new file descriptor corresponding to an existing open file description. Most properties between the old and new fd (like position) are shared; the only property I can think of that's not shared is the close-on-exec flag. The difference betweendupanddup2is thatdupassigns the lowest available file descriptor... |
I am using c .
I have fd1 as a file descriptor, can I call like this twice?
```
main () {
....
shutdown(fd1, SHUT_WR);
....
shutdown(fd1, SHUT_WR);
....
}
```
I personally think it works because fd1 has not been really free yet. Just want somebody to confirm.
|
You should check the return value of the second call -shutdown(2)probably returns-1- and check the value oferrno(3).
|
As the title implies basically: Say we have a complex program and we want to make it faster however we can. Can we somehow detect which loops or other parts of its structure take most of the time for targeting them for optimizations?
edit: Notice, of importance is that the software is assumed to be very complex and w... |
You're looking for a profiler. There are several around; since you mention gcc you might want to check gprof (part of binutils). There's alsoGoogle Perf Toolsalthough I have never used them.
|
I was looking at some c++ code, and I saw this:
```
int num = *(int *)number;
```
I had never seen this before?
it was in a function labeled as such:
```
void *customer(void *number){ }
```
What does that even do? Is there a different way to show this?
Thanks, this isn't homework btw I was just confused at what t... |
The (int *) part casts the variable number to a pointer to an int, then the * in front dereferences it to an int.
|
I have a codebase that makes extensive use of pthread.h. On a windows visual studio project, this obviously doesn't work since pthreads is a unix utility.
I know there exists pthread-win32 or something of the sort, but is there a way to have a codebase use this, without replacing all of the pthread code?
edit: I'd ... |
Tryhttp://sourceware.org/pthreads-win32/. While I've never used that particular library, I've had luck using some windows ports/abstraction layers of POSIX APIs.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:How do I tokenize a string in C++?
pseudocode:
```
Attributes[] = Split line(' ')
```
How?
I have been doing this:
```
char *pch;
pch = strtok(line," ");
while(pch!=NULL)
{
fputs ( pch, stdout );
}
```
and getting a n... |
Usestrtokwith" "as your delimiter.
|
When trying to compile this program:
```
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
printf("Hey there\n");
return 0;
}
```
i get compiler-error:
```
test.c:1:24: netinet/in.h: No such file or directory
test.c... |
You'll need to run cygwin's setup.exe again, and find the packages that contain the headers you need. Maybe there's a unix net package somewhere.
|
I'm looking for a runtime memory debugger, capable of showing memory usage (not just leaks) per function or line of C++ code on Linux.
I am trying to track down a spike in my program memory usage.
I have used Valgrind and Purify and I found that there are are no leaks. I expected that, as after that spike, the memory ... |
You can use the massif tool from the valgrind pack of tools.
|
I'm writing a simple web server in C on Linux.
I have to add the last modified time of a file that will be transferred to the client(browser),
I analysed how some websites and find out that they all present the time in format:
Fri, 12 Nov 2010 16:02:54 GMT,
my question is, can I transfer a time_t value to somethin... |
strftime() is the function you need.
The wikipedia article on time_t gives a good examplehttp://en.wikipedia.org/wiki/Time_t
|
I understand that & is used to reference the address of object so&char* = char**. Is there anyway to reverse this so that I can getchar*fromchar**?
So I have:
```
char** str; //assigned to and memory allocated somewhere
printf ("%s", str); //here I want to print the string.
```
How would I go about doing this?
|
You can use thedereference operator.
Thedereference operatoroperates on a pointer variable, and returns an l-value equivalent to the value at the pointer address. This is called "dereferencing" the pointer.
```
char** str; //assigned to and memory allocated somewhere
printf ("%s", *str); //here I want to print the ... |
Does OpenSSL have any support for operations in the quadratic extension field (or, alternatively, operations with complex numbers) using the BN API?
If not, are there any other open source libraries that do?
|
You may want to look atPBC. This is a library for computing pairings on some elliptic curves, which implies using field extensions of various degrees, including quadratic extensions for some fields.
|
I am using an Native library in android for streaming.
Here is the scenario:
I am passing a url to c file and after lot of processing it writes the data in wav file.
I'm not so much familiar with C but what i could understand is there is a pointer ofint16_tfrom which wav file is written.
Here is the question.
... |
I don't know the first thing about Android, but you might want to look intojava.nio.ByteBuffer- they can be made to allocate their buffer in native memory (allocateDirect()), so native functions can write directly into it.
|
I have a string, like "100110000111001100010001100011001100100" .
If I need to get the tail of this string, meaning everything but the first element,
do I have to copy each char to the new array, starting from the second element (O(n)),
or is there a faster way to do this, like somehow magically shift pointers 1 pl... |
If you don't need to make any modifications to the string then you can just give the original pointer plus 1, otherwise you will need to copy.
|
I would like to read the output of a zlib stream'sinflate()into a buffer one byte at a time, so that I can parse out single lines.
Is there a way to specify the number of bytes thatinflate()returns, so that I can watch for newlines?
|
That would probably give horrible performance, since theinflate()function might have some start up costs.
I would suggest just going with a reasonable output buffer size, and then iterating through the buffer after each call toinflate(), collecting all complete lines found. Of course there will very likely be a "tail... |
I wish to use the same socket fd for both read and write operations. Lets say the "fd" is the one which I am working on then in that case
```
FD_SET(fd, &readfd);
FD_SET(fd,&writefd);
select(fd+1, &readfd, &writefd, 0,200):
```
will hold good or it will return me the error.
I think since writefd and readfd are d... |
This is ok, and the proper way to monitor the same fd for both reading and writing. The last argument to select is a struct timeval though, not an integer.
|
This code gives me warnings:
```
$ cat test.c
#include<stdio.h>
#include<time.h>
int main() {
time_t t;
scanf("%lld", &t);
printf("%lld\n", t);
return 0;
}
$ gcc test.c -o test
test.c: In function ‘main’:
test.c:7: warning: format ‘%lld’ expects type ‘long long int *’, but argument 2 has type ‘time_... |
The exact type oftime_tdepends on your platform and OS. It's still quite often 32 bit (eitherintorlong), not 64, and some even use floats. The correct thing to do is to read into a known-size integer (eitherintorlong long) and then assign the value to atime_tas a second step.
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed12 years ago.
What do thedup()anddup2()system cal... |
Both make a new file descriptor corresponding to an existing open file description. Most properties between the old and new fd (like position) are shared; the only property I can think of that's not shared is the close-on-exec flag. The difference betweendupanddup2is thatdupassigns the lowest available file descriptor... |
I am using c .
I have fd1 as a file descriptor, can I call like this twice?
```
main () {
....
shutdown(fd1, SHUT_WR);
....
shutdown(fd1, SHUT_WR);
....
}
```
I personally think it works because fd1 has not been really free yet. Just want somebody to confirm.
|
You should check the return value of the second call -shutdown(2)probably returns-1- and check the value oferrno(3).
|
As the title implies basically: Say we have a complex program and we want to make it faster however we can. Can we somehow detect which loops or other parts of its structure take most of the time for targeting them for optimizations?
edit: Notice, of importance is that the software is assumed to be very complex and w... |
You're looking for a profiler. There are several around; since you mention gcc you might want to check gprof (part of binutils). There's alsoGoogle Perf Toolsalthough I have never used them.
|
I was looking at some c++ code, and I saw this:
```
int num = *(int *)number;
```
I had never seen this before?
it was in a function labeled as such:
```
void *customer(void *number){ }
```
What does that even do? Is there a different way to show this?
Thanks, this isn't homework btw I was just confused at what t... |
The (int *) part casts the variable number to a pointer to an int, then the * in front dereferences it to an int.
|
I have a codebase that makes extensive use of pthread.h. On a windows visual studio project, this obviously doesn't work since pthreads is a unix utility.
I know there exists pthread-win32 or something of the sort, but is there a way to have a codebase use this, without replacing all of the pthread code?
edit: I'd ... |
Tryhttp://sourceware.org/pthreads-win32/. While I've never used that particular library, I've had luck using some windows ports/abstraction layers of POSIX APIs.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:How do I tokenize a string in C++?
pseudocode:
```
Attributes[] = Split line(' ')
```
How?
I have been doing this:
```
char *pch;
pch = strtok(line," ");
while(pch!=NULL)
{
fputs ( pch, stdout );
}
```
and getting a n... |
Usestrtokwith" "as your delimiter.
|
When trying to compile this program:
```
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
printf("Hey there\n");
return 0;
}
```
i get compiler-error:
```
test.c:1:24: netinet/in.h: No such file or directory
test.c... |
You'll need to run cygwin's setup.exe again, and find the packages that contain the headers you need. Maybe there's a unix net package somewhere.
|
I'm looking for a runtime memory debugger, capable of showing memory usage (not just leaks) per function or line of C++ code on Linux.
I am trying to track down a spike in my program memory usage.
I have used Valgrind and Purify and I found that there are are no leaks. I expected that, as after that spike, the memory ... |
You can use the massif tool from the valgrind pack of tools.
|
I'm writing a simple web server in C on Linux.
I have to add the last modified time of a file that will be transferred to the client(browser),
I analysed how some websites and find out that they all present the time in format:
Fri, 12 Nov 2010 16:02:54 GMT,
my question is, can I transfer a time_t value to somethin... |
strftime() is the function you need.
The wikipedia article on time_t gives a good examplehttp://en.wikipedia.org/wiki/Time_t
|
I understand that & is used to reference the address of object so&char* = char**. Is there anyway to reverse this so that I can getchar*fromchar**?
So I have:
```
char** str; //assigned to and memory allocated somewhere
printf ("%s", str); //here I want to print the string.
```
How would I go about doing this?
|
You can use thedereference operator.
Thedereference operatoroperates on a pointer variable, and returns an l-value equivalent to the value at the pointer address. This is called "dereferencing" the pointer.
```
char** str; //assigned to and memory allocated somewhere
printf ("%s", *str); //here I want to print the ... |
Does OpenSSL have any support for operations in the quadratic extension field (or, alternatively, operations with complex numbers) using the BN API?
If not, are there any other open source libraries that do?
|
You may want to look atPBC. This is a library for computing pairings on some elliptic curves, which implies using field extensions of various degrees, including quadratic extensions for some fields.
|
I am using an Native library in android for streaming.
Here is the scenario:
I am passing a url to c file and after lot of processing it writes the data in wav file.
I'm not so much familiar with C but what i could understand is there is a pointer ofint16_tfrom which wav file is written.
Here is the question.
... |
I don't know the first thing about Android, but you might want to look intojava.nio.ByteBuffer- they can be made to allocate their buffer in native memory (allocateDirect()), so native functions can write directly into it.
|
I have a string, like "100110000111001100010001100011001100100" .
If I need to get the tail of this string, meaning everything but the first element,
do I have to copy each char to the new array, starting from the second element (O(n)),
or is there a faster way to do this, like somehow magically shift pointers 1 pl... |
If you don't need to make any modifications to the string then you can just give the original pointer plus 1, otherwise you will need to copy.
|
I would like to read the output of a zlib stream'sinflate()into a buffer one byte at a time, so that I can parse out single lines.
Is there a way to specify the number of bytes thatinflate()returns, so that I can watch for newlines?
|
That would probably give horrible performance, since theinflate()function might have some start up costs.
I would suggest just going with a reasonable output buffer size, and then iterating through the buffer after each call toinflate(), collecting all complete lines found. Of course there will very likely be a "tail... |
I wish to use the same socket fd for both read and write operations. Lets say the "fd" is the one which I am working on then in that case
```
FD_SET(fd, &readfd);
FD_SET(fd,&writefd);
select(fd+1, &readfd, &writefd, 0,200):
```
will hold good or it will return me the error.
I think since writefd and readfd are d... |
This is ok, and the proper way to monitor the same fd for both reading and writing. The last argument to select is a struct timeval though, not an integer.
|
Say I have my object layout defined as:
```
typedef struct {
PyObject_HEAD
// Other stuff...
} pyfoo;
```
...and my type definition:
```
static PyTypeObject pyfoo_T = {
PyObject_HEAD_INIT(NULL)
// ...
pyfoo_new,
};
```
How do I create a new instance ofpyfoosomewhere within my C extension?
|
CallPyObject_New(), followed byPyObject_Init().
EDIT:The best way is tocallthe class object, just like in Python itself:
```
/* Pass two arguments, a string and an int. */
PyObject *argList = Py_BuildValue("si", "hello", 42);
/* Call the class object. */
PyObject *obj = PyObject_CallObject((PyObject *) &pyfoo_T, ar... |
I have a string of characters that every 2 characters represent a hex value, for example:
```
unsigned char msg[] = "04FF";
```
I would like to Store the "04" in on byte and the FF in another byte?
The desire output should be similar to this,
```
unsigned short first_hex = 0x04;
unsigned second_hex = 0xFF;
memcp... |
unsigned char msg[] = { 0x04, 0xFF };
As for conversion from string, you need to read the string, two chars at a time:
```
usigned char result;
if (isdigit(string[i]))
result = string[i]-'0';
else if (isupper(string[i]))
result = string[i]-'A';
else if (islower(string[i]))
result = string[i]-'a';
```
mutiply ... |
I am very new to MySQL.
Linux.
I want to create a database in MySql and using a C program I would like to populate the data from a text file into the database.
I couldnt find much information on this :(
Is there any clear material on this? Can somebody please point me to the right direction?
Thanks.
|
MySQL comes with a client library and an ODBC connector. The client library is documented herehttp://dev.mysql.com/doc/refman/5.5/en/c-api-functions.html, the ODBC library is herehttp://dev.mysql.com/doc/refman/5.5/en/connector-odbc.html
|
What's the counter part of _wfopen? I found that there is fclose related to fopen, but it seems there is no _wfclose.
|
I would sayfclose(), since you don't actually need anything "wide" in order to close it.
|
InputString:"I am unwell" "We need to go to the doctor" "How long will it take?".
OutputString:I am unwell We need to go to the doctor How long will it take?
The string needs to cleaned of all occurrences of the char". I can think of the following approacg
Use, strchr() function finding first occurrence of"Move all... |
```
for (s=d=str;*d=*s;d+=(*s++!='"'));
```
|
Using only bitwise operators (|, &, ~, ^, >>, <<) and other basic operators like +, -, and !, is it possible to replace the "==" below?
```
int equal(int x, int y) {
return x == y;
}
```
|
Remember that anXORis the exactly same asNOT EQUALSandXNORis exactly the same asEQUALS. So, the following will give you exactly what you want:
```
return !(x ^ y);
```
|
Here is my code to generate values in the fibonnacci sequence below 10,000,000.
```
3 fibs = [1,1]
4 while((x = fibs[-1] + fibs[-2]) <= 10000000):
5 fibs.append(x)
```
I attempted to do C-style assignment of x in the while loop's condition. Unfortunately, python told me that it's a syntax error. What is the ... |
In Python, assignment is not an expression, and therefore has no value.
The simplest solution is to do the assignment in the first part of the loop:
```
fibs=[1,1]
while fibs[-1] <= 10000000:
fibs.append(fibs[-1] + fibs[-2])
```
|
I'm using a dsPic33F (16 bit microcontroller);
How to convertchar[]toint[]such that every two chars becomes an int using C++?and the inverse operation?
|
```
int* intArray = new int[sizeOfByteArray];
for (int i=0; i<sizeOfByteArray; ++i)
intArray[i] = byteArray[i];
```
Or
```
std::copy(byteArray, byteArray+sizeofByteArray, intArray);
```
|
If I run the command-line program mysql like
```
mysql -u someone -p < sql-file
```
so that a password is required (-p), it prompts for a password:
```
Enter password:
```
However, as you can see from the above, standard input is actually a file,sql-file.
How does "mysql" (or similar programs) do this?
(Please n... |
Open/dev/ttyas a file in read-mode, and then read from it.
|
In C, I understood that if we close a socket, it means the socket will be destroyed and can be re-used later.
How about shutdown? The description said it closes half of a duplex connection to that socket. But will that socket be destroyed likeclosesystem call?
|
This isexplainedin Beej's networking guide.shutdownis a flexible way to block communication in one or both directions. When the second parameter isSHUT_RDWR, it will block both sending and receiving (likeclose). However,closeis the way to actually destroy a socket.
Withshutdown, you will still be able to receive pe... |
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed8 years ago.Improve this question
hey i am trying to u... |
Stolen (and slightly modified) fromhere.
```
/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ");
while (pch != NULL)
{
printf ("%s\n",pch);
pch ... |
I'm looking for something similar to C++'sboost::bindbut in C. What I want is to be able to:
```
bound_function = bind(my_function, some_param);
```
and have:
```
bound_function(something);
```
execute
```
myfunction(some_param, something);
```
So basically, whatever is bound to the function pointer will always ... |
You couldn't do it the way C++ does it, because inboost::bind's case, a class is generated using TMP that holds the actual bound value.
I'm not aware of any way to accomplish anything similar in C. Most C APIs with callbacks like this will pass around avoid *for your use to get around issues like this.
|
I'm working on a programing assignment regarding using GET request.
I am using C.
I wonder if any headers fields and values of GET packet have to be capitalized?
For example:
```
GET / HTTP/1.1
Connection: Keep-Alive
```
vs
```
get / HTTP/1.1
connection: keep-alive
```
|
HTTP method names arecase-sensitive:
The Method token indicates the method
to be performed on the resource
identified by the Request-URI. The
method iscase-sensitive.
HTTP header names arecase-insensitive.
|
I've read that C89 does not support variable-length arrays, but the following experiment seems to disprove that:
```
#include <stdio.h>
int main()
{
int x;
printf("Enter a number: ");
scanf("%d", &x);
int a[x];
a[0] = 1;
// ...
return 0;
}
```
When I compile as such (assuming filename isva_test... |
GCC always supported variable length arrays AFAIK. Setting -std to C89 doesn't turn off GCC extensions ...
Edit: In fact if you check here:
http://gcc.gnu.org/onlinedocs/gcc/C-Dialect-Options.html#C-Dialect-Options
Under -std= you will find the following:
ISO C90 programs (certainGNU
extensions that conflict wit... |
I was just writing code in C and it turns out it doesn't have a boolean/bool datatype. Is there any C library which I can include to give me the ability to return a boolean/bool datatype?
|
If you have a compiler that supports C99 you can
```
#include <stdbool.h>
```
Otherwise, you can define your own if you'd like. Depending on how you want to use it (and whether you want to be able to compile your code as C++), your implementation could be as simple as:
```
#define bool int
#define true 1
#define f... |
I have two programs interacting via a shared memory segment. When using the segment for read or write, they hold a lock.
Should either of them crash (get killed, typically - possibly with something untrappable) in a critical section, I would like them to release the lock so that the shmem isn't locked out completely... |
I believe POSIX robust mutexes are what you're looking for:
http://www.opengroup.org/onlinepubs/9699919799/functions/pthread_mutexattr_getrobust.html
|
I have a function with an absurd number of return points, and I don't want to caveman each one, and I don't want to next through the function. Is there any way I can do something like finish, except have it stop on the return statement?
|
You can tryreverse debuggingto find out where function actually returns. Finish executing current frame, doreverse-stepand then you should stop at just returned statement.
```
(gdb) fin
(gdb) reverse-step
```
There is alreadysimilar question
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this question
My friend says it's possible to write a C program that will print "hello world" withoutIF... |
```
#include <stdio.h>
int main() {
switch (printf("Hello, world!\n")) {}
}
```
If your friend says "oh, you can't use switch either," then:
```
#include <stdio.h>
int main(int argc, char *argv[printf("Hello, world!\n")]) {}
```
|
If I have the follow 2 sets of code, how do I glue them together?
```
void
c_function(void *ptr) {
int i;
for (i = 0; i < 10; i++) {
printf("%p", ptr[i]);
}
return;
}
def python_routine(y):
x = []
for e in y:
x.append(e)
```
How can I call the c_function with a contiguous ... |
The following code works on arbitrary lists:
```
import ctypes
py_values = [1, 2, 3, 4]
arr = (ctypes.c_int * len(py_values))(*py_values)
```
|
If I were to define a statically allocated struct in place, I'd do:
struct mystructure x = {3, 'a', 0.3};
Is there a way I can do the same in C but using malloc. Ofcourse, I could do a
struct mystructure x = createNewMystruct(3, 'a', 0.3), (Where I'd define the createNewMyStruct function) but I would like to know if ... |
Closest I can think of is this:
```
struct mystructure *p = malloc(sizeof(*p));
assert(p);
*p = (const struct mystructure){3, 'a', 0.3};
```
C99 only, so don't come crying to me if it doesn't work in MSVC.
|
I'm trying to build an application using some of ffmpeg's libraries and I'm noticing many data structures with the word "Context" in them.
You can see some herehttp://www.ffmpeg.org/doxygen/trunk/classes.html
I don't understand the use of the word "context" in this.. context.
Any hints as to what it generally means... |
Looking at documentations you provided it seems related to the context of a particolar codec so that everySomethingContextencapsulates
the structs necessary for that particular codec (headers and so on)the available operations when wortking with that codec (which may vary according to the complexity of the codec itse... |
Using C or a bat file, I'm trying to edit the file hosts file from c:\Windows\System32\drivers\etc but I can;t bc it is write protected.
Can you tell me what can i do?
|
The program modifying the host file needs to run as Administrator
|
So for example: I have file.mp3, I know that my desired format can play sound with out video (for example FLV) so how to put encoded mp3 data using ffmpeg from mp3 container into flv (where to get articles/code samples on this)?
I mean not from cmd but from C++ using ffmpeg as library. (see tags)
|
Here is the command to convert .mp3 file to .flv(which does not have any video data).
ffmpeg -i test.mp3 -ab 32k -acodec libmp3lame -ac 1 -ar 44100 audio.flv.
You can execute this command from your program.
If you need help on how to install and use ffmpeg you can go to their site:
http://ffmpeg.org
Thanks,
Mah... |
```
int func(void) [5];
```
Why is above line not valid in c ? As anyone knows, function can be used as variable. But, I don't understand why compiler gives error .
Why I used that line is because I have tried to create 5 function-variable. To do so, I wrote like that, shown above.
|
Because it doesn't meet theC languagevalid syntax?
May be you should specifywhatare you trying to do with that sentence in order to get the answer you might be looking for.
|
```
#include<unistd.h>
int main(int argc, char **argv)
{
int ret;
ret = execve("/bin/bash", NULL, NULL);
return 0;
}
```
i m confuse about why the null values are passsed in execve
please help.....
|
Those parameters correspond to the program's arguments and environment. By passing NULL in for both, the caller is indicating that no arguments should be supplied to the program and no environment variables should be supplied either.
|
basically I want to return the number of digits in the int -> values like this:
```
(int)1 => 1
(int)123 => 3
(int)12345678 => 8
```
I know nothing about C, so please bear with me. I know objective c, but I use ints and floats instead of NSNumbers. I realise I could convert the ints into objective c objects, but thi... |
use
```
int d = (value == 0 ? 1 : (int)(log10(value)+1));
```
Note that this doesnt work for negative numbers, you'll have to use
```
int d = (value == 0 ? 1 : ((int)(log10(fabs(value))+1) + (value < 0 ? 1 : 0)));
```
which adds 1 for the minus sign, ifvalueis negative.
|
I want to initialize string in C to empty string.
I tried:
```
string[0] = "";
```
but it wrote
```
"warning: assignment makes integer from pointer without a cast"
```
How should I do it then?
|
In addition to Will Dean's version, the following are common for whole buffer initialization:
```
char s[10] = {'\0'};
```
or
```
char s[10];
memset(s, '\0', sizeof(s));
```
or
```
char s[10];
strncpy(s, "", sizeof(s));
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.