question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
While writing a simple server-client application, this question came in my mind. When someone tries to write to a broken pipe, a SIGPIPE would be generated. Let's say I handle the signal in my code.
Now what error does the write call returns - EPIPE or EINTR ( as it was interrupted by a signal). I tried with a sample... |
POSIX says that EPIPE should be returned and SIGPIPE sent:
For write()s or pwrite()s to pipes or FIFOs not open for reading by any process, or with only one end open.For write()s to sockets that are no longer connected or shut down for writing.
You can have a look at the POSIX standardhere
|
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.Closed13 years ago.
Take look at the code that follows.... |
These values go nowhere. You can not retrieve them. In fact, most are optimized out by the compiler.
That entire fragment can be simplified to atoi("232") because function calls usually can't be optimized out.
|
I am reading a binary file. and when it reaches the end. it seems it is terminated by feof() function. is it because there is no EOF character for binary files? if so how can i solve it.
currently my code is using a while loop
```
while (!feof(f))
```
when it reaches the end of file at position 5526900. it doesn't ... |
You should not use feof() to loop on - instead, use the return value of fread() - loop until it returns zero. This is easy to see if you consider reading an empty file - feof() returns the EOF status AFTER a read operation, so it will always try to read bogus data if used as a loop control.
I don't know why so many p... |
InPHPI can do it as simple as :
```
file_get_contents('http://stackoverflow.com/questions/ask');
```
What's the shortest code to do the same inC?
UPDATE
When I compile the sample with curl, got errors like this:
```
unresolved external symbol __imp__curl_easy_cleanup referenced in function _main
```
|
Uselibcurl, refer to theirexample C snippets
```
#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "curl.haxx.se");
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_clean... |
I'm using multithreading in my application with _beginthread and right now to wait until all threads are done I have global bools that get set to true as each thread completes so I'm in a while loop until then. There must be a cleaner way of doing this?
Thanks
|
You can useWaitForMultipleObjectsto wait for the threads to finish in primary thread.
|
I'm trying to read binary data in a C program with read() but EOF test doesn't work. Instead it keeps running forever reading the last bit of the file.
```
#include <stdio.h>
#include <fcntl.h>
int main() {
// writing binary numbers to a file
int fd = open("afile", O_WRONLY | O_CREAT, 0644);
int i;
for (i = ... |
readreturns the number of characters it read. When it reaches the end of the file, it won't be able to read any more (at all) and it'll return 0, not EOF.
|
There are many times that I get compile errors when I usechar*instead ofconst char*. So, I am not sure the actual difference, the syntax and the compile mechanism.
|
If you're after the difference between the two, just think of them as:
char*is a pointer that points to a location containing a value of type char that can also be changed. The pointer's value can be changed, i.e. the pointer can be modified to point to different locations.const char*is a pointer, whose value can be ... |
I want to define a macro which includes another header file like so:
```
#define MY_MACRO (text) #include "__FILE__##_inline.inl"
```
So that when the preprocessor parses file person.h, MY_MACRO(blahblah) expands to
#include "person.h.inline.inl"
any hints on how to do this ?
|
It's not possible to use#defineto construct other preprocessor directives, unless you run the preprocessor twice.
But in your case even running the preprocessor twice won't help because the#includemust be a single string of the form"..."or<...>.
|
This is a question for experienced C/C++ developpers.
I have zero knowledge of compiling C programs with "make", and need to modify an existing application, ie. change its "config" and "makefile" files.
The .h files that the application needs are not located in a single-level directory, but rather, they are spread i... |
This question appears to be about the C compiler driver, rather than make. Assuming you are using GCC, then you need to list each directory you want searched:
```
gcc -I/foo -I/foo/bar myprog.c
```
|
Maybe this has been asked before, but I couldn't find it. My question is simple: Does it make sense to write an application in higher level languages (Java, C#, Python) and time/performance-critical functions in C? Or at this point unless you do very low level OS/game/sensor programming it is all the same to have a fu... |
It makes sense if you a) notice a performance issue, AND b) use performance measurements to locate where the problem occurs, AND c) can't achieve the desired performance by modifying the existing code.
If any of these items don't apply, then it's probably premature optimization.
|
I am writing a program that repeatedly does an operation till Ctrl+C is hit by the user in the Linux terminal. I am programming in C. Any ideas how i can implement this.
I have tested my program by using "for" loops with a condition but now i want to make it run as long as Ctrl+C is hit by the user and interrupted.
... |
A signal trap will do the trick more cleanly than spudd86's suggestion. This example can be improved significantly, though.
```
#include <signal.h>
/* ... */
int execute;
void trap(int signal){ execute = 0; }
int main() {
/* ... */
signal(SIGINT, &trap);
execute = 1;
while(execute){
/* ... *... |
Is there any way to detect if I am connected to a VPN using standard windows APIs in C?
Basically I have a client that has to sync with a server but only if the VPN is connected. This could be a standard windows VPN client or a Citrix.
Is RAS helpful here?
thank you, code is appreciated.
EDIT:
to make it clearer.
... |
With the VPN I suspect you able to access resources that don't exists otherwise. So you could PING test a server on the VPN network. ICMP is the protocol for ping.
Here is some examples:http://www.alhem.net/project/ex10/index.html
|
Can I write simply
```
for (int i = 0; ...
```
instead of
```
int i;
for (i = 0; ...
```
in C or C++?
(And will variableibe accessible inside the loop only?)
|
It's valid in C++.
It was not legal in the original version of C.But was adopted as part of C in C99 (when some C++ features were sort of back ported to C)Using gcc
```
gcc -std=c99 <file>.c
```
The variable is valid inside the for statement and the statement that is looped over. If this is a block statement then i... |
when i try
```
char bla[32] = "foobar";
int i;
putchar(bla[i]);
```
withstrlen(bla) < i < 32,bla[i]is always\0. but isn't this in fact undefined behaviour, and should be avoided?
|
In section 6.7.8 of the C99 Standard, paragraph 21 states:
If there are fewer initializers in a
brace-enclosed list than there are
elements or members of an aggregate,
or fewer characters in a string
literal used to initialize an array of
known size than there are elements in
the array, the remainder of t... |
In c++, setw function is used to set the number of characters to be used as the field width for the next insertion operation. Is there any function in C, I mean, in standard c library, which does the same thing?
|
printf ("%5d", 42);
Will print 42 using 5 spaces. Read the man pages of printf to understand how character padding, overflow and other nuances work.
EDIT:
Some examples -
```
int x = 4000;
printf ("1234567890\n");
printf ("%05d\n", x);
printf ("%d\n", x);
printf ("%5d\n", x);
printf ("%2d\n", x);
```
Gives the out... |
```
char *a=NULL;
char *s=NULL;
a=(char *)calloc(1,(sizeof(char)));
s=(char *)calloc(1,(sizeof(char)));
a="DATA";
memcpy(s,a,(strlen(a)));
printf("%s",s);
```
Can you plz tell me why its printing DATA½½½½½½½½■ε■????How to print only DATA?? Thanks
|
Strings in C are terminated by a zero character value (nul).
strlen returns the number of characters before the zero.
So you are not copying the zero.
printf keeps going, printing whatever is in the memory after s until it hits a zero.
You also are only creating a buffer of size 1, so you are writing data over wha... |
I have made strcat() function myself but after adding the string it is printing an extra ascii symbol.
Please tell why?
```
#include<stdio.h>
#include<conio.h>
#include<string.h>
void xstrcat(char string1[],char string2[]);
void main(void)
{ char x[100];
char string1[40],string2[40];
printf("Enter a strin... |
Yourxstrcat()function isn't placing a null terminator character at the end of the resulting string.
One possible fix might be to put the following just before thexstrcat()function returns:
```
string1[x+y] = '\0';
```
|
I have the following
```
size_t i = 0;
uint32_t k = 0;
printf("i [ %lu ] k [ %u ]\n", i, k);
```
I get the following warning when compiling:
```
format ‘%lu’ expects type ‘long unsigned int’, but argument has type ‘uint32_t’
```
When I ran this using splint I got the following:
```
Format argument 1 to printf ... |
Try
```
#include <inttypes.h>
...
printf("i [ %zu ] k [ %"PRIu32" ]\n", i, k);
```
Thezrepresents an integer of length same assize_t, and thePRIu32macro,defined in the C99 headerinttypes.h, represents an unsigned 32-bit integer.
|
I want to make a program that forces it's user to input text but doesn't allow him to erase any of it, what's a simple way of doing it in C?
The only thing I've got is(c = getchar()) != EOF && c != '\b'which doesn't work. Any ideas?
|
POSIX - unix version
```
#include <sys/types.h>
#include <termios.h>
#include <stdio.h>
#include <string.h>
int
main()
{
int fd=fileno(stdin);
struct termios oldtio,newtio;
tcgetattr(fd,&oldtio); /* save current settings */
memcpy(&newtio, &oldtio, sizeof(oldtio));
... |
I have aFILE *, returned by a call tofopen(). I need to get a file descriptor from it, to make calls likefsync(fd)on it. What's the function to get a file descriptor from a file pointer?
|
The proper function isint fileno(FILE *stream). It can be found in<stdio.h>, and is a POSIX standard but not standard C.
|
I was browsing some code and I came across this macro definition
```
#define D(x) do { } while (0)
```
And its used in the code like this,
```
D(("couldn't identify user %s", user));
```
I ran the code, and that particular line doesn't do anything. So, why would some one define a macro like that?
In case you're w... |
Most likelyDis for debugging, and there's an#ifdefelsewhere that makes it do something more useful if debugging is enabled, like output the message or log it to a file. Thedo/whileloop is to make it require a semi-colon at the end, so the user can call it asD(...);instead of justD(...)(seethis post)
|
I've made a small application in C with Netbeans.
I've ran the application in Netbeans and it created an exe.
I used that exe and it worked fine on my comp but when I move it to other comp it says:
"This application failed to start because cygwin1.dll was not found. Re-installing the application may fix this problem."... |
The problem is you're using Cygwin GCC to compile your code. Cygwin provides a unix-like environment
if you're not doing anything Unix-y you can recomplie-mno-cygwin- seeCan you statically compile a cygwin application?if you are using Unix calls you'll need to distribute cygwin1.dll along with your appor you can reco... |
Which version of ANSI C standard does Turbo C 3.0 follow wholly or partly?
C89 or C90 ?
|
Turbo C++ 3.0 was released in 1991, which means that in its C compilation it probably supports K&R C and C89 (C90 was essentially identical). It won't support C95 well, because that version of the standard wasn't available.
|
i am trying to create a function likestrlen()in string.h
It's giving me the errorcan not convert char* to char
```
#include<stdio.h>
#include<conio.h>
int xstrlen(char string);
void main(void) {
char string[40];
puts("Enter string:");
gets(string);
printf(" %s is the length of %d", string, xstrlen(string))... |
Your prototype:
```
int xstrlen(char string);
```
Does not match the function definition:
```
int xstrlen(char string[]) { ... }
```
Change the prototype to:
```
int xstrlen(char string[]);
```
|
I need to create GdkPixBuf collection. I try to save pixbufs in GList - mw->disp_list:
```
GtkTreeIter iter;
int i = 0;
for (i; i < g_list_length(list) - 1; ++i)
{
char* file = image_list_get_current_file_path( list );
mw->p1 = gdk_pixbuf_new_from_file(file,NULL);
mw->p1 = scale_pix(mw... |
At the moment I see just one problem, and it is about the loop that should be:
```
for (i = 0; i < g_list_length(list); ++i)
```
The problem could be the -1: if list contains 1 element, you do not loop at all, since 1-1 = 0 and0 < 0is false.
|
I see there are many version of autoconf and automake available in my ubuntu linux.
If I want create a new project from scratch, what's best choice, latest versions or older versions?
|
Go with the latest version. It's only developers who are rebuilding the configure system that need to useautoconfandautomake(and thus need to have the newer version installed), which likely just means "you"; it won't affect users who are just building your project using your distributed configure files.
|
I have just noticed about a librarySFIOfor a safe and fast IO processing in C. But it is not very up to date. The last version of library is released in20052012and I couldn't assess that if the claimed benefits of SFIO over STDIO are still valid with comparison to the recent releases of standard IO library. Also Would... |
I would prefer using standard stuffs instead of relying on a lib that is not maintained or developed anymore. Do tests however to know if your code really benefits from its usage. If it is not hard, develop your code with switches definible at compile time to usesfioor the standard approach, so that you can switch to ... |
I need to generate values according to time of the day, is there a neat way to accomplish that ?
from 9-12 value should be between x - y
from 6-9 value should be between a - b
is there any other way than getting timeinfo struct and extracting hour out of it?
|
You should take a look atboost::posix_time.
```
using namespace boost::posix_time;
using namespace boost::gregorian;
ptime now = second_clock::local_time();
// You can compare now with other ptime values
ptime nine_o_clock = day_clock::local_day() + hours(9);
ptime twelve_o_clock = day_clock::local_day() + hours(12... |
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.Closed13 years ago.
```
#include<stdio.h>
main()
{
in... |
It's casting the pointer to be viewed as a pointer to char, then adding 4 to look at something 4 char's later in memory, and finally dereferencing the result. In a typical case whereintoccupies 4 bytes, it'll look at the first byte of the secondintin the array. Thatcharwill be promoted to anint, passed toprintf, and p... |
I'm writing a little pong clone with ncurses and C.
I need to find a way to set the keyboard repeat delay to make it easier for a player to move the paddle, otherwise they are stuck hitting the down key and waiting about 50 milliseconds until the key begins to repeat.
I've checked the ncurses man pages and documentat... |
How about capturing the keydown and the repeatedly checking to see if the key is up yet?
|
Microsoft's docs say:
Specifies that the corresponding point
in lpPoints is a control point or
ending point for a Bèzier curve.
PT_BEZIERTO values always occur in sets of three. The point in
the path immediately preceding them
defines the starting point for the
Bèzier curve. The first two
PT_BE... |
It's a cubic with shared endpoints. p[0], p[1], p[2], p[3] make up the first segment; p[3], p[4], p[5], and p[6] make up the second segment. And so forth.
|
What code do we use to move at a point on the screen in graphics mode(graphics.h)?As in normal we use goto(x,y).
|
Since you don't have a choice in the matter, here are some tutorials on drawing stuff withgraphics.h:
Part 1Part 2Part 3
|
I'd like the compiler to output a file containing the pointers to all global variables in the source code it is compiling, and also the sizes of them.
Is this possible? Is there a way to do it in any c compiler?
|
Something like a map file? That will show where the globals and statics are allocated, but not what they point at. Most compilers (linkers) will output one automatically or with a simple statement. Just search for map file in your documentation.
|
gcc 4.4.4 c89
I am using the code below. However, I keep getting the same number:
```
size_t i = 0;
for(i = 0; i < 3; i++) {
/* Initialize random number */
srand((unsigned int)time(NULL));
/* Added random number (simulate seconds) */
add((rand() % 30) + 1);
}
```
I would lik... |
You're seedinginsidethe loop (with the same value because of how quickly the loop will be executed), which causes the random number generated to be the same each time.
You need to move your seed functionoutsidethe loop:
```
/* Initialize random number */
srand((unsigned int)time(NULL));
for(i = 0; i < 3; i++) {
... |
I have made strcat() function myself but after adding the string it is printing an extra ascii symbol.
Please tell why?
```
#include<stdio.h>
#include<conio.h>
#include<string.h>
void xstrcat(char string1[],char string2[]);
void main(void)
{ char x[100];
char string1[40],string2[40];
printf("Enter a strin... |
Yourxstrcat()function isn't placing a null terminator character at the end of the resulting string.
One possible fix might be to put the following just before thexstrcat()function returns:
```
string1[x+y] = '\0';
```
|
I have the following
```
size_t i = 0;
uint32_t k = 0;
printf("i [ %lu ] k [ %u ]\n", i, k);
```
I get the following warning when compiling:
```
format ‘%lu’ expects type ‘long unsigned int’, but argument has type ‘uint32_t’
```
When I ran this using splint I got the following:
```
Format argument 1 to printf ... |
Try
```
#include <inttypes.h>
...
printf("i [ %zu ] k [ %"PRIu32" ]\n", i, k);
```
Thezrepresents an integer of length same assize_t, and thePRIu32macro,defined in the C99 headerinttypes.h, represents an unsigned 32-bit integer.
|
I want to make a program that forces it's user to input text but doesn't allow him to erase any of it, what's a simple way of doing it in C?
The only thing I've got is(c = getchar()) != EOF && c != '\b'which doesn't work. Any ideas?
|
POSIX - unix version
```
#include <sys/types.h>
#include <termios.h>
#include <stdio.h>
#include <string.h>
int
main()
{
int fd=fileno(stdin);
struct termios oldtio,newtio;
tcgetattr(fd,&oldtio); /* save current settings */
memcpy(&newtio, &oldtio, sizeof(oldtio));
... |
I have aFILE *, returned by a call tofopen(). I need to get a file descriptor from it, to make calls likefsync(fd)on it. What's the function to get a file descriptor from a file pointer?
|
The proper function isint fileno(FILE *stream). It can be found in<stdio.h>, and is a POSIX standard but not standard C.
|
I was browsing some code and I came across this macro definition
```
#define D(x) do { } while (0)
```
And its used in the code like this,
```
D(("couldn't identify user %s", user));
```
I ran the code, and that particular line doesn't do anything. So, why would some one define a macro like that?
In case you're w... |
Most likelyDis for debugging, and there's an#ifdefelsewhere that makes it do something more useful if debugging is enabled, like output the message or log it to a file. Thedo/whileloop is to make it require a semi-colon at the end, so the user can call it asD(...);instead of justD(...)(seethis post)
|
I've made a small application in C with Netbeans.
I've ran the application in Netbeans and it created an exe.
I used that exe and it worked fine on my comp but when I move it to other comp it says:
"This application failed to start because cygwin1.dll was not found. Re-installing the application may fix this problem."... |
The problem is you're using Cygwin GCC to compile your code. Cygwin provides a unix-like environment
if you're not doing anything Unix-y you can recomplie-mno-cygwin- seeCan you statically compile a cygwin application?if you are using Unix calls you'll need to distribute cygwin1.dll along with your appor you can reco... |
Which version of ANSI C standard does Turbo C 3.0 follow wholly or partly?
C89 or C90 ?
|
Turbo C++ 3.0 was released in 1991, which means that in its C compilation it probably supports K&R C and C89 (C90 was essentially identical). It won't support C95 well, because that version of the standard wasn't available.
|
i am trying to create a function likestrlen()in string.h
It's giving me the errorcan not convert char* to char
```
#include<stdio.h>
#include<conio.h>
int xstrlen(char string);
void main(void) {
char string[40];
puts("Enter string:");
gets(string);
printf(" %s is the length of %d", string, xstrlen(string))... |
Your prototype:
```
int xstrlen(char string);
```
Does not match the function definition:
```
int xstrlen(char string[]) { ... }
```
Change the prototype to:
```
int xstrlen(char string[]);
```
|
I need to create GdkPixBuf collection. I try to save pixbufs in GList - mw->disp_list:
```
GtkTreeIter iter;
int i = 0;
for (i; i < g_list_length(list) - 1; ++i)
{
char* file = image_list_get_current_file_path( list );
mw->p1 = gdk_pixbuf_new_from_file(file,NULL);
mw->p1 = scale_pix(mw... |
At the moment I see just one problem, and it is about the loop that should be:
```
for (i = 0; i < g_list_length(list); ++i)
```
The problem could be the -1: if list contains 1 element, you do not loop at all, since 1-1 = 0 and0 < 0is false.
|
I see there are many version of autoconf and automake available in my ubuntu linux.
If I want create a new project from scratch, what's best choice, latest versions or older versions?
|
Go with the latest version. It's only developers who are rebuilding the configure system that need to useautoconfandautomake(and thus need to have the newer version installed), which likely just means "you"; it won't affect users who are just building your project using your distributed configure files.
|
I have just noticed about a librarySFIOfor a safe and fast IO processing in C. But it is not very up to date. The last version of library is released in20052012and I couldn't assess that if the claimed benefits of SFIO over STDIO are still valid with comparison to the recent releases of standard IO library. Also Would... |
I would prefer using standard stuffs instead of relying on a lib that is not maintained or developed anymore. Do tests however to know if your code really benefits from its usage. If it is not hard, develop your code with switches definible at compile time to usesfioor the standard approach, so that you can switch to ... |
I need to generate values according to time of the day, is there a neat way to accomplish that ?
from 9-12 value should be between x - y
from 6-9 value should be between a - b
is there any other way than getting timeinfo struct and extracting hour out of it?
|
You should take a look atboost::posix_time.
```
using namespace boost::posix_time;
using namespace boost::gregorian;
ptime now = second_clock::local_time();
// You can compare now with other ptime values
ptime nine_o_clock = day_clock::local_day() + hours(9);
ptime twelve_o_clock = day_clock::local_day() + hours(12... |
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.Closed13 years ago.
```
#include<stdio.h>
main()
{
in... |
It's casting the pointer to be viewed as a pointer to char, then adding 4 to look at something 4 char's later in memory, and finally dereferencing the result. In a typical case whereintoccupies 4 bytes, it'll look at the first byte of the secondintin the array. Thatcharwill be promoted to anint, passed toprintf, and p... |
I'm writing a little pong clone with ncurses and C.
I need to find a way to set the keyboard repeat delay to make it easier for a player to move the paddle, otherwise they are stuck hitting the down key and waiting about 50 milliseconds until the key begins to repeat.
I've checked the ncurses man pages and documentat... |
How about capturing the keydown and the repeatedly checking to see if the key is up yet?
|
Microsoft's docs say:
Specifies that the corresponding point
in lpPoints is a control point or
ending point for a Bèzier curve.
PT_BEZIERTO values always occur in sets of three. The point in
the path immediately preceding them
defines the starting point for the
Bèzier curve. The first two
PT_BE... |
It's a cubic with shared endpoints. p[0], p[1], p[2], p[3] make up the first segment; p[3], p[4], p[5], and p[6] make up the second segment. And so forth.
|
What code do we use to move at a point on the screen in graphics mode(graphics.h)?As in normal we use goto(x,y).
|
Since you don't have a choice in the matter, here are some tutorials on drawing stuff withgraphics.h:
Part 1Part 2Part 3
|
I'd like the compiler to output a file containing the pointers to all global variables in the source code it is compiling, and also the sizes of them.
Is this possible? Is there a way to do it in any c compiler?
|
Something like a map file? That will show where the globals and statics are allocated, but not what they point at. Most compilers (linkers) will output one automatically or with a simple statement. Just search for map file in your documentation.
|
i am trying to create a function likestrlen()in string.h
It's giving me the errorcan not convert char* to char
```
#include<stdio.h>
#include<conio.h>
int xstrlen(char string);
void main(void) {
char string[40];
puts("Enter string:");
gets(string);
printf(" %s is the length of %d", string, xstrlen(string))... |
Your prototype:
```
int xstrlen(char string);
```
Does not match the function definition:
```
int xstrlen(char string[]) { ... }
```
Change the prototype to:
```
int xstrlen(char string[]);
```
|
I need to create GdkPixBuf collection. I try to save pixbufs in GList - mw->disp_list:
```
GtkTreeIter iter;
int i = 0;
for (i; i < g_list_length(list) - 1; ++i)
{
char* file = image_list_get_current_file_path( list );
mw->p1 = gdk_pixbuf_new_from_file(file,NULL);
mw->p1 = scale_pix(mw... |
At the moment I see just one problem, and it is about the loop that should be:
```
for (i = 0; i < g_list_length(list); ++i)
```
The problem could be the -1: if list contains 1 element, you do not loop at all, since 1-1 = 0 and0 < 0is false.
|
I see there are many version of autoconf and automake available in my ubuntu linux.
If I want create a new project from scratch, what's best choice, latest versions or older versions?
|
Go with the latest version. It's only developers who are rebuilding the configure system that need to useautoconfandautomake(and thus need to have the newer version installed), which likely just means "you"; it won't affect users who are just building your project using your distributed configure files.
|
I have just noticed about a librarySFIOfor a safe and fast IO processing in C. But it is not very up to date. The last version of library is released in20052012and I couldn't assess that if the claimed benefits of SFIO over STDIO are still valid with comparison to the recent releases of standard IO library. Also Would... |
I would prefer using standard stuffs instead of relying on a lib that is not maintained or developed anymore. Do tests however to know if your code really benefits from its usage. If it is not hard, develop your code with switches definible at compile time to usesfioor the standard approach, so that you can switch to ... |
I need to generate values according to time of the day, is there a neat way to accomplish that ?
from 9-12 value should be between x - y
from 6-9 value should be between a - b
is there any other way than getting timeinfo struct and extracting hour out of it?
|
You should take a look atboost::posix_time.
```
using namespace boost::posix_time;
using namespace boost::gregorian;
ptime now = second_clock::local_time();
// You can compare now with other ptime values
ptime nine_o_clock = day_clock::local_day() + hours(9);
ptime twelve_o_clock = day_clock::local_day() + hours(12... |
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.Closed13 years ago.
```
#include<stdio.h>
main()
{
in... |
It's casting the pointer to be viewed as a pointer to char, then adding 4 to look at something 4 char's later in memory, and finally dereferencing the result. In a typical case whereintoccupies 4 bytes, it'll look at the first byte of the secondintin the array. Thatcharwill be promoted to anint, passed toprintf, and p... |
I'm writing a little pong clone with ncurses and C.
I need to find a way to set the keyboard repeat delay to make it easier for a player to move the paddle, otherwise they are stuck hitting the down key and waiting about 50 milliseconds until the key begins to repeat.
I've checked the ncurses man pages and documentat... |
How about capturing the keydown and the repeatedly checking to see if the key is up yet?
|
Microsoft's docs say:
Specifies that the corresponding point
in lpPoints is a control point or
ending point for a Bèzier curve.
PT_BEZIERTO values always occur in sets of three. The point in
the path immediately preceding them
defines the starting point for the
Bèzier curve. The first two
PT_BE... |
It's a cubic with shared endpoints. p[0], p[1], p[2], p[3] make up the first segment; p[3], p[4], p[5], and p[6] make up the second segment. And so forth.
|
What code do we use to move at a point on the screen in graphics mode(graphics.h)?As in normal we use goto(x,y).
|
Since you don't have a choice in the matter, here are some tutorials on drawing stuff withgraphics.h:
Part 1Part 2Part 3
|
I'd like the compiler to output a file containing the pointers to all global variables in the source code it is compiling, and also the sizes of them.
Is this possible? Is there a way to do it in any c compiler?
|
Something like a map file? That will show where the globals and statics are allocated, but not what they point at. Most compilers (linkers) will output one automatically or with a simple statement. Just search for map file in your documentation.
|
gcc 4.4.4 c89
I am using the code below. However, I keep getting the same number:
```
size_t i = 0;
for(i = 0; i < 3; i++) {
/* Initialize random number */
srand((unsigned int)time(NULL));
/* Added random number (simulate seconds) */
add((rand() % 30) + 1);
}
```
I would lik... |
You're seedinginsidethe loop (with the same value because of how quickly the loop will be executed), which causes the random number generated to be the same each time.
You need to move your seed functionoutsidethe loop:
```
/* Initialize random number */
srand((unsigned int)time(NULL));
for(i = 0; i < 3; i++) {
... |
I am writing a client using libsoup APIs.
I have done the following.
```
session = soup_session_sync_new();
msg = soup_message_new("GET","http://www.google.com");
status = soup_session_send_message(session,msg);`
```
However now i am getting the following error code in status. I print the reason phrase and it sa... |
The problem was i use a proxy server to connect to internet. Hence i needed to set the session object property of SOUP_SESSION_PROXY_URI with the proxy-sever:port value.
It works fine now. Time to test POST method now.
|
People usevoid main() /*empty parens ()*/
I have been taught to writevoid main(void)
Any ideas what the difference is?
|
I'm not sure what the standards are nowadays, but in traditional ANSI C, using empty parentheses indicates that the function can takeanynumber of arguments. Declaring avoidparameter on the other hand indicates that the functiononly takes zero arguments. In this case (and many others), it really doesn't matter too much... |
Is there any standardized structure of C source and header files?
I'm thinking about something like this (example for C source file):
// static variables
// public variables
// static methods
// public methods
|
This is a totally subjective question. However, here's what I do approximately.
Header:
```
// extern defines, constants and enums
// public types
// extern methods
```
There are no extern variables :-)
Compilation unit:
```
// includes
// definitions for extern constants
// static function prototypes
// everyth... |
which of these two is better?
```
void SetBit(int *flag, int bit)
{
*flag |= 1 << bit;
}
```
Or
```
int SetBit(int flag, int bit)
{
flag |= 1 << bit;
return flag;
}
```
|
I like the second one because it doesn't have any side effects. If you want to modifyflag, you can simply assign the result to itself:
```
flag = SetBit(flag, 4);
```
|
My funciton takes a number input from the user and recursively sums the number 'n' to one.Inputting a 5 would sum 1/5 + 1/4 + 1/3+ 1/2 + 1/1.
```
#include<stdio.h>
#include<conio.h>
//to
float recursion(float num,float sum);
void main(void)
{
float num=5,sum=0;
//input num
printf("%d",recursion(num,sum));
g... |
You should return the result of the recursive call:
```
return recursion(num,sum);
```
instead ofreturn sum.
|
I currently have inline functions calling another inline function (a simple 4 lines biggetAbs()function). However, I discovered by looking to the assembler code that the "big" inline functions are well inlined, but the compiler use abljump to call thegetAbs()function.
Is it not possible to inline a function in anothe... |
Depending on what compiler you are using you may be able to encourage the compiler to be less reluctant to inline, e.g. with gcc you can use__attribute__ ((always_inline)), with Intel ICC you can useicc -inline-level=1 -inline-forceinline, and with Apple's gcc you can usegcc -obey-inline.
|
i use gconf/gconf-client.h in ,y C application, but i don't know, is gconf on users machine. How can i check gconf/gconf-client.h and gconf there or not?
Thank you
|
If the code compiles then probably its already installed. Otherwise you can download the package and install it.
If you use thepkg-config --cflags gconf-2.0and compile, gcc will give corresponding error if the package doesnt exist in the PKG_CONFIG_PATH.
|
If I want to explode a string by parts in PHP into an array, I have the nifty explode() function where I just do the following
```
$mystring = "HI:THERE:HOW";
$stringarray = explode(":", $mystring);
```
And I get
```
$stringarray = (
[0] = "HI"
[1] = "THERE"
[2] = "HOW"
);
```
Is there a similar function in ... |
```
NSArray *stringArray = [myString componentsSeparatedByString:@":"];
```
|
I create my VBO like this:
```
glGenBuffersARB(1,&polyvbo);
glBindBufferARB(GL_ARRAY_BUFFER_ARB,polyvbo);
glBufferDataARB(GL_ARRAY_BUFFER_ARB,sizeof(GLfloat) * tempvct.size(),&tempvct[0],GL_DYNAMIC_COPY);
```
Then to update it I just do the same thing:
```
glBindBufferARB(GL_ARRAY_BUFFER_ARB,polyvbo);
... |
It doesn't cause a memory leak because the buffer is not reallocated.
But why not useglBufferSubData()? it will probably be much faster and does basically the same thing.
|
I get a segfault from this line of code:
```
int fatblob[1820][286][5];
```
Why is that?
|
Because your stack segment is smaller then1820*285*5ints. It's usually in a neighborhood of 1MB.
|
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.Closed10 years ago.
i have question on this topic i th... |
The value3051in decimal is101111101011in binary. If you split it up into four bit segmens like this:1011 1110 1011, you see that the lowest four bits are repeated above the eight bits that you want. The reason for that is that you haven't masked the value that should be the top four bits.
So instead of something like... |
gcc 4.4.4 c89
I have seen this in some code I am maintaining.
```
#define FALSE 0
#define TRUE (!FALSE)
```
is there any difference in writing the following:
```
#define FALSE 0
#define TRUE 1
```
Its been used in some functions like this:
```
if(condition failed) {
return FALSE;
}
else {
return TRUE;
}
... |
One difference is, in the(!FALSE)case, if you change:
```
#define FALSE 0
```
to
```
#define FALSE 1
```
Your program still "works", without modifying TRUE... however, it's unlikely that would be safe anyways, because I'm sure your program relies on constructs such as
```
if (funtion_that_returns_FALSE()) {
}
```... |
Is it possible to decompile third-party shared libraries built for solaris into C code?
|
Sort of. The short answer is: not really well.
The long answer is to read what REC and other "reverse" compilers do.
Maybe try here REC:
http://www.backerstreet.com/rec/rec.htm
try Rational Rose as well:
http://www.slac.stanford.edu/BFROOT/www/Computing/Environment/Tools/Rose.html
They can create C. or C++. W... |
This question already has answers here:Closed13 years ago.
Possible Duplicate:Garbage Collection in C++ — why?
Hi, I read few articles about Garbage Collectors, and still there is one thing I just don´t understand - why use garbage collection?
I will try to explain my thoughts:
Garbage Collector should release dyn... |
To be more productive. In other words, the programmer can focus on writing the bits that is unique for his particular problem.
|
If I want to explode a string by parts in PHP into an array, I have the nifty explode() function where I just do the following
```
$mystring = "HI:THERE:HOW";
$stringarray = explode(":", $mystring);
```
And I get
```
$stringarray = (
[0] = "HI"
[1] = "THERE"
[2] = "HOW"
);
```
Is there a similar function in ... |
```
NSArray *stringArray = [myString componentsSeparatedByString:@":"];
```
|
I create my VBO like this:
```
glGenBuffersARB(1,&polyvbo);
glBindBufferARB(GL_ARRAY_BUFFER_ARB,polyvbo);
glBufferDataARB(GL_ARRAY_BUFFER_ARB,sizeof(GLfloat) * tempvct.size(),&tempvct[0],GL_DYNAMIC_COPY);
```
Then to update it I just do the same thing:
```
glBindBufferARB(GL_ARRAY_BUFFER_ARB,polyvbo);
... |
It doesn't cause a memory leak because the buffer is not reallocated.
But why not useglBufferSubData()? it will probably be much faster and does basically the same thing.
|
I get a segfault from this line of code:
```
int fatblob[1820][286][5];
```
Why is that?
|
Because your stack segment is smaller then1820*285*5ints. It's usually in a neighborhood of 1MB.
|
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.Closed10 years ago.
i have question on this topic i th... |
The value3051in decimal is101111101011in binary. If you split it up into four bit segmens like this:1011 1110 1011, you see that the lowest four bits are repeated above the eight bits that you want. The reason for that is that you haven't masked the value that should be the top four bits.
So instead of something like... |
gcc 4.4.4 c89
I have seen this in some code I am maintaining.
```
#define FALSE 0
#define TRUE (!FALSE)
```
is there any difference in writing the following:
```
#define FALSE 0
#define TRUE 1
```
Its been used in some functions like this:
```
if(condition failed) {
return FALSE;
}
else {
return TRUE;
}
... |
One difference is, in the(!FALSE)case, if you change:
```
#define FALSE 0
```
to
```
#define FALSE 1
```
Your program still "works", without modifying TRUE... however, it's unlikely that would be safe anyways, because I'm sure your program relies on constructs such as
```
if (funtion_that_returns_FALSE()) {
}
```... |
Is it possible to decompile third-party shared libraries built for solaris into C code?
|
Sort of. The short answer is: not really well.
The long answer is to read what REC and other "reverse" compilers do.
Maybe try here REC:
http://www.backerstreet.com/rec/rec.htm
try Rational Rose as well:
http://www.slac.stanford.edu/BFROOT/www/Computing/Environment/Tools/Rose.html
They can create C. or C++. W... |
This question already has answers here:Closed13 years ago.
Possible Duplicate:Garbage Collection in C++ — why?
Hi, I read few articles about Garbage Collectors, and still there is one thing I just don´t understand - why use garbage collection?
I will try to explain my thoughts:
Garbage Collector should release dyn... |
To be more productive. In other words, the programmer can focus on writing the bits that is unique for his particular problem.
|
For purposes of type checking I would like to define a function on the lines of
```
void myfunc(type1 a, type2 b)
{
...
}
```
wheretype1andtype2are both typedefed touint8_t. So far so good, but for sanity and checking purposes (think DbC) I would like to prevent the function being called with atype2value for the fi... |
You could wrap the two types in a Struct.
```
typedef struct {
uint8_t data;
} type1;
typedef struct {
uint8_t data;
} type2;
```
Edit:
I don't like it because you now have to use a.data instead of a
|
Using inline assembler [gcc, intel, c], how to check if the carry flag is set after an operation?
|
sbb %eax,%eaxwill store -1 in eax if the carry flag is set, 0 if it is clear. There's no need to pre-clear eax to 0; subtracting eax from itself does that for you. This technique can be very powerful since you can use the result as a bitmask to modify the results of computations in place of using conditional jumps.
Y... |
How can I imposeGdkDrawingAreaon theGtkImagefor painting on an image, for example?
|
GtkDrawingAreaandGtkImageare different classes, so you must choose one of them. You can still draw onGtkImage(and on any other widget), by connecting toexpose_eventsignal.
You could also use plainGtkDrawingArea- displaying image is a matter of callinggdk_draw_pixbuffunction.
|
I have the following code which initiate the thread.
```
int iNMHandleThread = 1;
HANDLE hNMHandle = 0;
hNMHandle = CreateThread( NULL, 0, NMHandle, &iNMHandleThread, 0, NULL);
if ( hNMHandle == NULL)
ExitProcess(iNMHandleThread);
```
My question is
What will happened if I run this code while the thread already in ... |
Each time you callCreateThread, a new thread is started that is independent of any other currently-running threads. Whether your "NMHandle" function is capable of running on more than one thread at a time is up to you: for example, does it rely on any global state?
|
I need to get the millisecond accuracy. I take a look onthis questionbut I am working on Windows: it gives linking errors for POSIX functions.
It will be very good if I can get UTC time since 1970 with milliseconds precision.
|
Not in ANSI C, but the Windows API provides aGetSystemTimefunction as illustrated here:https://learn.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-systemtime
|
I have one basic doubt.
I have a process which uses a shared library. If I am allocating some memory in the library
then which address space it is. (Library or Process)
In my opinion it is the process address space because once the library is attached it is all in process address space.
Please correct me if I am wro... |
A library doesn't have its own address space. It is mapped into and executed within some process. So you are right. Memory allocations of a shared library are done inside the process which is using it.
|
Is there a way to declare first and then initialize an array in C?
So far I have been initializing an array like this:
```
int myArray[SIZE] = {1,2,3,4....};
```
But I need to do something like this
```
int myArray[SIZE];
myArray = {1,2,3,4....};
```
|
In C99 you can do it using a compound literal in combination withmemcpy
```
memcpy(myarray, (int[]) { 1, 2, 3, 4 }, sizeof myarray);
```
(assuming that the size of the source and the size of the target is the same).
In C89/90 you can emulate that by declaring an additional "source" array
```
const int SOURCE[SIZE]... |
I would like to know how the contents of a file can be cleared in C. I know it can be done usingtruncate, but I can't find any source clearly describing how.
|
The other answers explain how to usetruncatecorrectly... but if you found yourself on a non-POSIX system that doesn't haveunistd.h, then the easiest thing to do is just open the file for writing and immediately close it:
```
#include <stdio.h>
int main()
{
FILE *file = fopen("asdf.txt", "w");
if (!file)
... |
My application is rendering about 100 display lists / second. While I do expect this to be intensive for the gpu, I don't see why it brings my cpu up to 80 - 90 %. Arn't display lists stored in the graphics card and not in system memory? What would I have to do to reduce this crazy cpu usage? My objects never change s... |
If you are referring tothese, then I suspect the bottleneck is going to be CPU related. All the decoding of such files is done on the CPU. Sure, each individual command might result in several commands to your graphics card, which will execute quickly, but the CPU is stuck doing decoding duty.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:Why there is not a comprehensive c archive network?
Everyone knows that C is very small language, it has just language primitives and almost no standard library (no data structures or algorithms).
Therefore I have a question, how do I fin... |
GLib.
|
Using Glib Testing framework, I would like to know if I can reuse a pointer queued to be freed with g_test_queue_free?
Here's a code sample of what I'm trying to do:
```
static void some_test()
{
gchar* tmp;
tmp = func_returning_gchar_ptr (...params...);
g_assert(tmp);
g_test_queue_free(tmp);
tmp = func_... |
Yes that should be fine
|
Which is the global variable which holds all the environmental variables for getenv() ? In what glibc file is this var filled with env vars ?
I believe it to be **environ but when I set an env var in bash it only ouputs the SSH_AGENT_PID env var. Why is SSH_AGENT_PID set and why is it the only one that is set ?
```... |
char **environisNULL-terminated array of strings, so you should try:
```
extern char **environ;
char **p;
for (p = environ; *p; p++) {
printf ("%s\n", *p);
}
```
In other words,environ[0]is pointer to first env variable,environ[1]to second etc. Last element inenvironarray isNULL.
|
In c lets say we have 2 files
1.h
```
#include<2.h>
blah blah
```
and we have
2.h
```
#include<1.h>
code
```
How is this resolved??
|
Typically you protect your include file with an ifndef/define that corresponds to the file name. This doesn't prevent the file from being included again, but it does prevent the contents (inside the ifndef) from being used and triggering the recursive includes again.
```
#ifndef HEADER_1_h
#define HEADER_1_h
#inc... |
Is there someone that knows what the computational cost for this two pieces of code is?
```
while (n > 2)
n = sqrt(n);
while (n > 2)
n = log(n);
```
|
The second would beO(log* n)wherelog *is theiterated logarithm.
Analysing the first one yields something like this:
```
sqrt(n) = n ^ (1/2)
sqrt(sqrt(n)) = n ^ (1/4)
sqrt(sqrt(sqrt(n))) = n ^ (1/8)
...
sqrt applied k times = n ^ (1/2^k)
```
Consider that the first algorithm executesktimes (basically, the number of ... |
Is there a C function that can concatenate all the passed arguments (except the name of the executable) into achar*and return it?
|
Try that:
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv) {
unsigned int i;
size_t len = 0;
char *_all_args, *all_args;
for(i=1; i<argc; i++) {
len += strlen(argv[i]);
}
_all_args = all_args = (char *)malloc(len+argc-1);
for(i=1; i... |
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... |
There is no such thing as a user-mode FS filter.
You could write aminifilter driverthat delegates the computing (of the I/O operation verdict) to a user mode componentthrough a portand reports back the result.You can check out/src/filesystem/miniFilter/scannersample in theWinDDK.
|
Suppose I do asystem("ps-C nautilus");how do I return the result of this function in char* ?
Thank you.
|
You don't. Not sure what platform you're on, but have a look at thepopenfunction instead. You'll get a bidirectional pipe this way, which you can do file operations on, like reading to get a string out of it.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.