question
stringlengths
25
894
answer
stringlengths
4
863
Using below code I reading data from socket. On the other side the Java client sending string data. But while reading the data an additional \n appears at the end of the string. Can anyone explain why this happen. Code: ``` unsigned char buf[100]; rd=read(newsockfd,buf,100); char cmd[30]; sprintf(cmd,"%s",buf...
My guess here would be that the newline comes from the Java client itself. Probably the client is using a function likesendLine(String)or something thatadds a newline to the string passed to it before sending it on the network. I don't know Java but this seems very likely.
I installed a windows service with cygwin cygrunsrv. That service is writing something to a file every 5 seconds. After I tried it, I removed service with "cygrunserv -R service_name". Now, service is removed from services list but it is still running. How can I remove it for real.
Restarting Windows is solving that issue.
I just can't find an algorithm to split the string into words by numerous delimiters. I know how to split a string by whitespace withistringtreamand bysingle delimiterwithgetline. How can I connect them all. For instance: input:This -is-a!,string;output: ``` This is a string ```
Why not just#include <cstring>and usestd::strtok()in your C++ program?
I am new in C and I have the following simple code. I know that with the strncpy I can copy characters from string. ``` #include <stdio.h> #include <string.h> int main () { char str1[]= "To be or not to be"; char str2[40]; strncpy ( str2, str1, 5 ); str2[5] = '\0'; /* null character manually added */ pu...
Use : ``` strncpy ( str2, str1+6, 9); str2[9] = '\0'; /* null character manually added */ ```
this is more of a general question. Is there any performance penalty of usingLINEandFILEin logging related functions? i have been using them exclusively like this: in c++ ``` Logger::debug("Incoming msg from rs232,__LINE__, __FILE__); ``` and my program has been running extremely slow..i just wanted to confirm if r...
No, not at all. They are macros that expand into some constant. __LINE__expands into the line number as a decimal integer constant and__FILE__to a C string constant.
Just a beginner question. I tried to find an answer to this but I couldn't. Why ``` for (int i = 0;i==10;++i) { /* body of the for loop */ } ``` Never executes the body of the for loop? but this one works? ``` for (int i = 0;i<=10;++i) { /* body of the for loop */ } ``` The (i==0) should be a boolean expression e...
C++ 101: The middle condition must be true for the loop to continue.
I've searched around, but I haven't found any valuable information regarding this error. ``` typedef struct { unsigned short string[]; } s; const s str = { .string = L"George Morgan" }; ``` SOLUTION: ``` typedef struct { int string[]; } s; const s str = { .string = L"George ...
A string literal prefixed withLis stored in an array ofwchar_tand you'll fix the error you observed by using it. You need to include the headerwchar.hto access it. Also,sizeof(s)is a constant, so it clearly cannot depend on what string it is initialized with. From this it is easy to see, that you must provide the arra...
I'm reading "Learning Core Audio: A Hands-On Guide to Audio Programming for Mac and iOS" by Chris Adamson and at one point the author describes big-endian as: the high bits of a byte or word are numerically more significant than the lower ones. However, until now I thought the problem of big-little endian only appli...
Since you can't normally address the bits within a byte individually, there's no concept of "bit endianness" generally.
I've an input string consisting of space separated numbers like "12 23 34".Output should be an array of integers. I tried the following: ``` while (sscanf(s, "%d", &d) == 1) { arr[n++] = d; } ``` But I found that since I'm not reading from file (where offsets are adjusted automatically),I keep storing the same ...
scanfprovides an elegant answer: the%nconversion, which tells you how many bytes have been consumed so far. Use it like this: ``` int pos; while (sscanf(s, "%d%n", &d, &pos) == 1) { arr[n++] = d; s += pos; } ```
I have a question regarding to the function declaration: I declared a function in b.c ``` //b.c void getNumber(); //common header common.h ``` In a.c I use it like this: //a.c ``` #include "common.h" void getInfo() { getNumber(); } ``` but it complain the getNumber is implicit declaration of function, what is...
add the following line tocommon.h ``` void getNumber(); ``` the b.c file should contain the function definition in this way ``` void getNumber() { .... } ```
Using below code I reading data from socket. On the other side the Java client sending string data. But while reading the data an additional \n appears at the end of the string. Can anyone explain why this happen. Code: ``` unsigned char buf[100]; rd=read(newsockfd,buf,100); char cmd[30]; sprintf(cmd,"%s",buf...
My guess here would be that the newline comes from the Java client itself. Probably the client is using a function likesendLine(String)or something thatadds a newline to the string passed to it before sending it on the network. I don't know Java but this seems very likely.
I installed a windows service with cygwin cygrunsrv. That service is writing something to a file every 5 seconds. After I tried it, I removed service with "cygrunserv -R service_name". Now, service is removed from services list but it is still running. How can I remove it for real.
Restarting Windows is solving that issue.
I just can't find an algorithm to split the string into words by numerous delimiters. I know how to split a string by whitespace withistringtreamand bysingle delimiterwithgetline. How can I connect them all. For instance: input:This -is-a!,string;output: ``` This is a string ```
Why not just#include <cstring>and usestd::strtok()in your C++ program?
I am new in C and I have the following simple code. I know that with the strncpy I can copy characters from string. ``` #include <stdio.h> #include <string.h> int main () { char str1[]= "To be or not to be"; char str2[40]; strncpy ( str2, str1, 5 ); str2[5] = '\0'; /* null character manually added */ pu...
Use : ``` strncpy ( str2, str1+6, 9); str2[9] = '\0'; /* null character manually added */ ```
this is more of a general question. Is there any performance penalty of usingLINEandFILEin logging related functions? i have been using them exclusively like this: in c++ ``` Logger::debug("Incoming msg from rs232,__LINE__, __FILE__); ``` and my program has been running extremely slow..i just wanted to confirm if r...
No, not at all. They are macros that expand into some constant. __LINE__expands into the line number as a decimal integer constant and__FILE__to a C string constant.
Just a beginner question. I tried to find an answer to this but I couldn't. Why ``` for (int i = 0;i==10;++i) { /* body of the for loop */ } ``` Never executes the body of the for loop? but this one works? ``` for (int i = 0;i<=10;++i) { /* body of the for loop */ } ``` The (i==0) should be a boolean expression e...
C++ 101: The middle condition must be true for the loop to continue.
I've searched around, but I haven't found any valuable information regarding this error. ``` typedef struct { unsigned short string[]; } s; const s str = { .string = L"George Morgan" }; ``` SOLUTION: ``` typedef struct { int string[]; } s; const s str = { .string = L"George ...
A string literal prefixed withLis stored in an array ofwchar_tand you'll fix the error you observed by using it. You need to include the headerwchar.hto access it. Also,sizeof(s)is a constant, so it clearly cannot depend on what string it is initialized with. From this it is easy to see, that you must provide the arra...
I'm reading "Learning Core Audio: A Hands-On Guide to Audio Programming for Mac and iOS" by Chris Adamson and at one point the author describes big-endian as: the high bits of a byte or word are numerically more significant than the lower ones. However, until now I thought the problem of big-little endian only appli...
Since you can't normally address the bits within a byte individually, there's no concept of "bit endianness" generally.
I've an input string consisting of space separated numbers like "12 23 34".Output should be an array of integers. I tried the following: ``` while (sscanf(s, "%d", &d) == 1) { arr[n++] = d; } ``` But I found that since I'm not reading from file (where offsets are adjusted automatically),I keep storing the same ...
scanfprovides an elegant answer: the%nconversion, which tells you how many bytes have been consumed so far. Use it like this: ``` int pos; while (sscanf(s, "%d%n", &d, &pos) == 1) { arr[n++] = d; s += pos; } ```
I just can't find an algorithm to split the string into words by numerous delimiters. I know how to split a string by whitespace withistringtreamand bysingle delimiterwithgetline. How can I connect them all. For instance: input:This -is-a!,string;output: ``` This is a string ```
Why not just#include <cstring>and usestd::strtok()in your C++ program?
I am new in C and I have the following simple code. I know that with the strncpy I can copy characters from string. ``` #include <stdio.h> #include <string.h> int main () { char str1[]= "To be or not to be"; char str2[40]; strncpy ( str2, str1, 5 ); str2[5] = '\0'; /* null character manually added */ pu...
Use : ``` strncpy ( str2, str1+6, 9); str2[9] = '\0'; /* null character manually added */ ```
this is more of a general question. Is there any performance penalty of usingLINEandFILEin logging related functions? i have been using them exclusively like this: in c++ ``` Logger::debug("Incoming msg from rs232,__LINE__, __FILE__); ``` and my program has been running extremely slow..i just wanted to confirm if r...
No, not at all. They are macros that expand into some constant. __LINE__expands into the line number as a decimal integer constant and__FILE__to a C string constant.
Just a beginner question. I tried to find an answer to this but I couldn't. Why ``` for (int i = 0;i==10;++i) { /* body of the for loop */ } ``` Never executes the body of the for loop? but this one works? ``` for (int i = 0;i<=10;++i) { /* body of the for loop */ } ``` The (i==0) should be a boolean expression e...
C++ 101: The middle condition must be true for the loop to continue.
I've searched around, but I haven't found any valuable information regarding this error. ``` typedef struct { unsigned short string[]; } s; const s str = { .string = L"George Morgan" }; ``` SOLUTION: ``` typedef struct { int string[]; } s; const s str = { .string = L"George ...
A string literal prefixed withLis stored in an array ofwchar_tand you'll fix the error you observed by using it. You need to include the headerwchar.hto access it. Also,sizeof(s)is a constant, so it clearly cannot depend on what string it is initialized with. From this it is easy to see, that you must provide the arra...
I'm reading "Learning Core Audio: A Hands-On Guide to Audio Programming for Mac and iOS" by Chris Adamson and at one point the author describes big-endian as: the high bits of a byte or word are numerically more significant than the lower ones. However, until now I thought the problem of big-little endian only appli...
Since you can't normally address the bits within a byte individually, there's no concept of "bit endianness" generally.
I've an input string consisting of space separated numbers like "12 23 34".Output should be an array of integers. I tried the following: ``` while (sscanf(s, "%d", &d) == 1) { arr[n++] = d; } ``` But I found that since I'm not reading from file (where offsets are adjusted automatically),I keep storing the same ...
scanfprovides an elegant answer: the%nconversion, which tells you how many bytes have been consumed so far. Use it like this: ``` int pos; while (sscanf(s, "%d%n", &d, &pos) == 1) { arr[n++] = d; s += pos; } ```
I am using libgit2 via an FFI in another language but I am having difficulty figuring out what various functions actually do (and I'd prefer not to resort to reading the source code unless absolutely necessary). Does anyone know where I can find some working code samples for some of the functions in libgit2?
There are many ways to help you get a start with libgit2: Aseries of postsfrom Ben Straub, one of the core contributorsTaking a peek at the libgit2exampleswhich are written in a very easily understandable C codeReading through theheaderswhich describe each function, expected parameters and produced outputAnother angl...
What would be an alternative for Microsoft C++ compiler's#importdirective in a C (notC++) source code? Are there any tools which automatically produce C interfaces from a given type library?
The closest I know is using the OLE/COM object viewer (OLEVIEW.EXE) to get part of the IDL back, correcting a few missing things, and then running that through MIDL again.
Is it possible to print out what is stored at a specific memory address? For example I want to know what is stored at the address 0x7FFFFF0. How would I do this? I do not know what is stored at the address before hand ie. it could be an int or char or a null terminator.
Depending on your environment, you may be able to simply declare a pointer and dereference it: ``` volatile unsigned int *p = (volatile unsigned int *)0x7FFFFF0; printf("%u\n", *p); ``` This operation requires your program to have permission to access that memory, of course. Your mileage may vary on different opera...
I have used dig to see dns query related information but now I need to find some APIs for dns query by which I would be able to get specifically SOA record of my query programatically in C. Last option I can try by reading socket and parsing the format. But if someone tell me about any function and APIs of c on linux...
The first thing to try is theres_*API. This is part of the Unix C library since 4.3BSD, which means it's very portable (as long as you don't care about Windows)butit's also somewhat, er, inconvenient to work with (in particular you have to parse query responses with only minimal library assistance) and doesn't suppor...
I have the following struct defined: ``` typedef struct { int a; } A; typedef struct { int b; } B; typedef struct { A a, B b[10]; } C; ``` while thesizeof(C)will besizeof(A) + sizeof(B) * 10? I want to have the whole size of the struct C, how to get it?
sizeof(C)will be at leastsizeof(A) + sizeof(B) * 10 Aggregate types may be bigger due to alignment issues. Probably not in this case, given we're really talking about 11 ints.
Is it possible to write a message on assert error? For example, using#include <assert.h>, I can only write: ``` void foo(int a, int b) { assert (a != b); } ``` However, on an error I want to see the value ofaandb. How can I do that?
I usually simply useassert(a != b && "This is my error message"). This works becausechar*can be converted to bool and that it never will be false (since the address is not 0).
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question Can C or C++ be used to program a library in python? I know that python can be used to write a library but ...
Definitely. There are lots of high performance libraries written in C (simplejson being a notable and fairly simple example.) Seehttp://wiki.python.org/moin/IntegratingPythonWithOtherLanguages
I have implemented a TFTP on top of UDP in C, and I am trying to figure out how to check the read/write permission on thedirectorythat transfer is going to take place. For the existence of the file and the case that file doesn't exist I have used access() with F_OK, but W_OK and R_OK seem to be troublesome when trying...
Idea of an alternative: You don't need to check the permission for the directory; just try to open the file, and send the resulting error code.
I want to use threads withpthreadin C. One question I have about threads is why mutex lock does not block the execution when the whole application relays on one shared ressource? Bodo
You want thepthread_mutex_trylock()function. The pthread_mutex_trylock() function shall be equivalent to pthread_mutex_lock(), except that if the mutex object referenced by mutex is currently locked (by any thread, including the current thread), the call shall return immediately. Refere...
to read bmp files we may use thishttp://msdn.microsoft.com/en-us/library/dd183376(VS.85).aspxas the header file and then get rgb triplets. How to get the rgb triplets of jpeg file, is there any such header file available. Please share the link if any.
The JPEG file format does not store the rgb triplets directly but it uses some sort of image compression. The file actually contains blocks of 64 (if I remember correctly) pixels which are attributed with a cosine pattern defining the actual colors. You really should use a library (libjpeg, imagemagick, gd, ... e.g.,...
Why the same width&height images don't have the same sizes? As I understand they both have the same amount of pixels, don't they? So why can one weigh more than the other?
In the Bitmap format (files with extension .bmp): The header size could be different. (In header, the file format, image size, image color type, and such kind of additional information is stored.)The size for one pixel could be different. 1 bit/pixel for black/white images. 8 bit/pixel for at-most-256-color images. 2...
Ok, so hopefully I do not look like an idiot from asking this question...as it is quite basic, but my brain is either on vacation or something is indeed wrong. So-4 % 5or-4 mod 5should equal1correct? Why is it that thefmodfunction from the math.h library returns-4when you use it, i.efmod(-4, 5)returns-4instead of1. I...
The%operator is theremainderoperator, not modulo. Thefmodfunction is also the floating pointremainder, not modulo. In this case, they have selected to round -4/5 toward 0 to an integer.
I'm trying to make a program that finds the root of an equation. Everything about my program works just fine, except for the equation itself: it keeps returning wrong values (1, infinity, 0, ...). This is the function I'm evaluating: ``` double f(x) { return exp(-x)-sin(M_PI*x/2.); } ``` For example, f(.3) shou...
``` double f(x) { return exp(-x)-sin(M_PI*x/2.); } ``` The type for x is not declared, so it defaults toint. You pass.3, so it coerced tointand become 0. ``` exp(-0)-sin(M_PI*0/2.) == exp(0)-sin(0) == 1.0-0 == 1.0 ``` Please find yourself a better compiler, and turn on warnings.
I would like to create a new pty session in Linux, like as gnome-terminal xterm and others do. Half of my task is working, I created a pty session with openpty, fork()-ed a process, child uses the slave FD, and the remaining process terminal attach to a network socket. Through the network I can connect to "remote ter...
PassNULLas thestruct termios *argument toopenpty()(orforkpty(), which you should look into!), and the resulting defaults should be reasonable for an interactive terminal.
I am using libgit2 via an FFI in another language but I am having difficulty figuring out what various functions actually do (and I'd prefer not to resort to reading the source code unless absolutely necessary). Does anyone know where I can find some working code samples for some of the functions in libgit2?
There are many ways to help you get a start with libgit2: Aseries of postsfrom Ben Straub, one of the core contributorsTaking a peek at the libgit2exampleswhich are written in a very easily understandable C codeReading through theheaderswhich describe each function, expected parameters and produced outputAnother angl...
What would be an alternative for Microsoft C++ compiler's#importdirective in a C (notC++) source code? Are there any tools which automatically produce C interfaces from a given type library?
The closest I know is using the OLE/COM object viewer (OLEVIEW.EXE) to get part of the IDL back, correcting a few missing things, and then running that through MIDL again.
Is it possible to print out what is stored at a specific memory address? For example I want to know what is stored at the address 0x7FFFFF0. How would I do this? I do not know what is stored at the address before hand ie. it could be an int or char or a null terminator.
Depending on your environment, you may be able to simply declare a pointer and dereference it: ``` volatile unsigned int *p = (volatile unsigned int *)0x7FFFFF0; printf("%u\n", *p); ``` This operation requires your program to have permission to access that memory, of course. Your mileage may vary on different opera...
I have used dig to see dns query related information but now I need to find some APIs for dns query by which I would be able to get specifically SOA record of my query programatically in C. Last option I can try by reading socket and parsing the format. But if someone tell me about any function and APIs of c on linux...
The first thing to try is theres_*API. This is part of the Unix C library since 4.3BSD, which means it's very portable (as long as you don't care about Windows)butit's also somewhat, er, inconvenient to work with (in particular you have to parse query responses with only minimal library assistance) and doesn't suppor...
I have the following struct defined: ``` typedef struct { int a; } A; typedef struct { int b; } B; typedef struct { A a, B b[10]; } C; ``` while thesizeof(C)will besizeof(A) + sizeof(B) * 10? I want to have the whole size of the struct C, how to get it?
sizeof(C)will be at leastsizeof(A) + sizeof(B) * 10 Aggregate types may be bigger due to alignment issues. Probably not in this case, given we're really talking about 11 ints.
Is it possible to write a message on assert error? For example, using#include <assert.h>, I can only write: ``` void foo(int a, int b) { assert (a != b); } ``` However, on an error I want to see the value ofaandb. How can I do that?
I usually simply useassert(a != b && "This is my error message"). This works becausechar*can be converted to bool and that it never will be false (since the address is not 0).
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question Can C or C++ be used to program a library in python? I know that python can be used to write a library but ...
Definitely. There are lots of high performance libraries written in C (simplejson being a notable and fairly simple example.) Seehttp://wiki.python.org/moin/IntegratingPythonWithOtherLanguages
I have the following code: ``` #include <stdio.h> #include <stdlib.h> typedef struct { int a[3]; } A; typedef struct { int b; } B; typedef struct { A a; B b; } C; void getC(C *c_p) { C c; c.a.a[0] = 1; c.b.b = 1; memcpy(c_p, &c, sizeof(C)); } int main() { C *c; getC(c); } ``...
The error is in yourmain, where you pass an uninitialized pointer togetC. You should make it point to something, like this: ``` C c; getC(&c); ``` or ``` C *c = malloc(sizeof(C)); getC(c); ... free(c); ``` Moreover, you do not need to usememcpywithstructs - an assignment will work as well: ``` void getC(C *c_p) {...
I have this code for swapping elements: ``` atomic{ int temp = a[i]; a[i] =a[j]; a[j] = temp; } ``` How would I implement this using fine-grained locking to achieve the same effect?
You can use mutex to achieve this effect, ``` mutex.lock(); atomic { int temp = a[i]; a[i] =a[j]; a[j] = temp; } mutex.unlock(); ``` If there are multiple threads you can use POSIX style Read/Write locks as follows, ``` pthread_rwlock_rdlock(rw_lock_ptr); atomic { int temp = a[i]; a[i] =a[j]; a[j]...
Today I got a irritating question in a coding contest. I creamed through the first round but in the second round the following question got me in a trap. ``` Question: Input N = 4 Output: 1 0 1 1 0 1 0 1 0 1 ``` I tried many things but eve...
Seems pretty trivial to me: ``` int main(int argc, char *argv[]) { int n = strtol(argv[1], NULL, 10); for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { printf("%d ", i % 2 ? j % 2 : 1 - j % 2); } printf("\n"); } return 0; } ```
I am trying to run a C program in Ubuntu via command prompt, I can run successfully using ``` ./aaa<arg_file.txt Content of arg_file.txt a bb ccc ``` It displays the result successfully, but this time I do not want to use the txt file to pass the parameters, instead I want to pass all the arguments using one single...
If your shell is Bash or compatible, use the<<[SENTINEL]syntax: ``` h2co3-macbook:~ h2co3$ cat <<EOF > abc > def > ghi > EOF abc def ghi h2co3-macbook:~ h2co3$ ```
I am trying to find out what is the difference between using aselect()function andFD_ISSETcall. What are the different scenarios that justify using either of them?
Anfd_setis a bit array used as input in calls toselect. FD_ISSETis used to check whether a specific bit is set in anfd_set. selectis used to poll all file descriptors that correspond to bit that are set in anfd_set. A typical scenario will be to: Create and clear anfd_set. Set bits for the file descriptors you wa...
``` typedef struct { char nazwisko[30]; double srednia; int semestr; }osoba; void WyszukiwanieSemestr(osoba *stud, int sem, int i) { int a; printf("\n"); for(a=0;a<i;++a) { if(stud[a].semestr == sem) { printf("%d. %s %.3lf %d\n",a+1,stud[a].nazwisko,stud[a].srednia,...
``` scanf("%d",sem); ``` should be ``` scanf("%d", &sem); ```
I want to know if there is a way to read date from console in format dd.mm.yyyy in C. I have a structure with information for the date. I tried with another structure just for the date with day, month and year in it: ``` typedef struct { int day; int month; int year; } Date; ``` but the dots are a probl...
Try: ``` Date d; if (scanf("%d.%d.%d", &d.day, &d.month, &d.year) != 3) error(); ```
My question about using functions withstruct. I took the snippet from R.Stevens' book and I saw similar snippets a couple of time. I suggest to get some C and Linux experience, but I really do not know how to use struct in right way in this case. ``` struct stat buf; // The error line for (i=1; i < arg...
You forgot to include: ``` #include <sys/types.h> #include <sys/stat.h> ```
Code: ``` #include <stdio.h> #include <unistd.h> int main(void) { char buf[BUFSIZ]; int n; while((n = read(0, buf, BUFSIZ)) > 0 && printf("1:%d ", n)) { printf("2:%d ", n); write(1, buf, n); } return 0; } pupu(my input) pupu(output) popopo(my input) popopo(output) 1:5 2:5 1...
The standard I/O functions (likeprintf) arebuffered, meaning output tostdoutisn't printed until its buffer is full or explicitly flushed. On the other hand, writing directly to the output file descriptor isnotbuffered and is written directly. What you have here is you mixing direct and buffered output, and the buffe...
I would like to write assert statement but not abort the program. So perhaps use exact same syntax as assert() but called expect(). Of course I can write my own, but assert is quite clever (e.g. it knows not only the file and line number but even the expression which is not TRUE). I could of course dig into the libr...
It's becauseassertis a preprocessor macro, and so can use the__LINE__and__FILE__macros as the whole macro invocation is expanded into a single line. You can easily make your own: ``` #define expect(value, message) \ do \ { \ if (!(value)) \ { \ fprintf(stderr, "%s failed in %s:%d\...
Is it possible to develop a H.264 to HEVC transcoder for asterisk as it doesn't have native support for H.265/HEVC ? If so, how would I put my transcoder into use?
Too long to put in a comment... asterisk?? Answering without knowing anything about that FW. I'd say no, since although H.264 and HEVC share a large set of functions they are fundamentally different. In H.264 the fundamental area to operate on is the macroblock. The MB concept doesn't exist anylonger in HEVC. Then a...
I have written the following code to multiply two numbers and I see the result to be incorrect. I assume the data type is not holding the value right. But the answer its printing is incorrect. ``` #include<stdio.h> main() { long int val1,val2; val1=val2=1235; char c = 'y'; switch(c) { case...
Data type is holding the right value but you are using the wrong specifier. You should use%ldwith long int. printf("%20ld",val1*val2); I double checked and it worked.
``` const char *SITE_NAME = "test"; char SITE_ROOT[19]; sprintf (SITE_ROOT, "/var/www/html/%s", SITE_NAME); ``` I can't figure out why I'm getting an error of: error: expected ‘)’ before string constant Basically I just want to concatenate the variable SITE_NAME onto SITE_ROOT. The error is on the sprintf line. Any...
The error looks like it might not be shown in the code but thesprintfshould be: ``` sprintf (SITE_ROOT, "/var/www/html/%s", SITE_NAME); ``` EDIT: Here is my complete test code if that helps at all: ``` #include <string.h> #include <stdio.h> int main() { const char *SITE_NAME = "test"; char SITE_ROOT[19]; ...
Look at the following code: ``` char chs[100] = "Hello World"; char token[100]; int pos = -1; while((current = chs[++pos]) != '"'){ strcat(token, &current); } ``` But the output is : ``` H\001e\001l\001l\001o\001 \001W\001o\001r\001l\001d ``` Any ideas?
strcat() needs a null-terminated string as it's input. so strcat(token, &current) will start reading at the address of current and keep going until it finds a null. Just by chance, what you had in memory after current was "\001", so each time you did strcat it copied all that into token. You should do char current[]...
My program will be a list of names and surnames. I have a a struct which has attributes of name, surname, and a pointer to the next struct object. In for loop I will add a new items to this 'list', just by writing new names in the command line (for that I will use scanf). I would like to ask how co create this list...
I'll assume your structure for storing a name isstruct name. You'll probably have a variable to store the head of the list: ``` struct name *head; ``` We want to append to the end of the list. One way to do this would be to store a pointer to where we want to put the pointer to the next node: ``` struct name **tail...
I have the struct: ``` struct person { char firstname[]; }; ``` And the method: ``` void abcde (person* a, char firstchar[]) { a->firstname = firstchar; } ``` The gcc throws this: incompatible types in assignment ofchar*' tochar[0u]' How to solve this problem? Thanks for help!
You cannot assign to an array. you want either a pointer, or copy the content of one into another. ``` struct person { char* firstname; }; void abcde (person* a, char firstchar[]) { a->firstname = firstchar; } ``` firstcharin the function parameters is apointer, not an array! the[]is merely a syntactic con...
This question already has answers here:Why is “while( !feof(file) )” always wrong?(5 answers)C programming task, html source file(1 answer)Closed9 years ago. I am trying to scan file by using while loop: ``` while(feof(src_file) == 0){ } ``` This method works perfectly fine if there is only one row in scanned file...
http://www.cplusplus.com/reference/cstdio/feof/as this says the error is cleared by some api calls a better check is fgetc(src_file) != EOF
how to write this ASM code in C? ``` loc_536FB0: mov cl, [eax] cmp cl, ' ' jb short loc_536FBC cmp cl, ',' jnz short loc_536FBF loc_536FBC: mov byte ptr [eax], ' ' loc_536FBF mov cl, [eax+1] inc eax test cl, cl jnz short loc_536FB0 ``` I have figured out that it is a for loop counting to 23 then exiting.
``` char *str; // = value of eax int i = 0; while (str[i]) { if (str[i] < ' ' || str[i] == ',') str[i] = ' '; i++; } ``` It traverses a c-string and replaces all characters below' 'and commas','with a space' '. See anASCII table: characters "below" space are all the controll characters. The function p...
The malloc example I'm studying is ``` #include <stdio.h> #include <stdlib.h> int main() { int *vec; int i, size; printf("Give size of vector: "); scanf("%d",&size); vec = (int *) malloc(size * sizeof(int)); for(i=0; i<size; i++) vec[i] = i; for(i=0; i<size; i++) printf("vec[%d]: %d\n", i, vec[i]); free(vec)...
It is dynamic memory allocation. The very important point there is thatyou don't know how much memory you'll needbecause the amount of memory you must end up with is dependant on the user input. Thus the use of malloc, which takessizeas part of its argument, andsizeis unknown at compile-time.
Whyfread()doesn't work butfwrite()works? If I getfwrite()into comments andfread()out of comments, the output file is of0 bytessize... But iffwrite()is out of comments, the output file is of64 bytessize.. What is the matter? ``` #include <stdio.h> #include <stdlib.h> int main() { FILE *input = fopen( "01.wav", ...
You should read from your input file, and write to your output file. ``` char buf[64]; fread(buf, 1, sizeof(buf), input); fwrite(buf, 1, sizeof(buf), output); ``` Your code should check the return values offreadandfwritefor errors.
I have heard many times that C and Python/Ruby code can be integrated. Now, my question is, can I use, for example a Python/Ruby ORM from within C?
Yes, but the API would be unlikely to be very nice, especially because the point of an ORM is to returnobjectsand C doesn't have objects, hence making access to the nice OOP API unwieldy. Even in C++ is would be problematic as the objects would be Python/Ruby objects and the values Python/Ruby objects/values, and you...
I understand that every process has a logical clock C, a->b if C(a) < C(b). But how do they start the processes to work? Here we have an image: Do they use messaging? We start at the process P1 and it sends a message to P2? Then what P2 does? What did P2 before getting request from P1?
P1, P2 and P3 work on the following principle: They all increment independently, but at different frequencies (and aim for synchronization). When an event occurs, the originating process sends its current value to the target process, which checks whether the value received is smaller than its current value. If ...
This question already has answers here:Complex C declaration(8 answers)Closed9 years ago. So I have the following expression ``` int *(*table())[30]; ``` In my opinion table() return a value which points to the beginning of an array of pointers which each element points to an integer. What do you think? Thanks.
You're correct. According tocdecl ``` int *(*table())[30]; ``` declare table as function returning pointer to array 30 of pointer to int See also theclockwise/spiralorright-leftrules for help understanding C expressions (and see comments below for some points in favour of the latter).
I have a c++ commandline program that writes a list of data to file as part of a validation process like this: ``` fprintf(code,"%s\t%s\t%5.3f\t%5.3f\t%5.3f\t\n", the_five_variables_the_data_comes_from ``` This happens in a for loop and I'd like to check programatically if two subsequent lines match. My question is ...
Usesprintfto format into an intermediate string before writing it to the file. Keep each iteration stored in a 'previous' variable and compare it against current. Something like this: ``` char previous[SIZE]; *previous = '\0'; for (...) { char buffer[SIZE]; sprintf(buffer, "...", ...); if (strcmp(previo...
I'm currently trying to compile my project just after adding some C code. I'm using the Paul Kocher's blowfish algorithm implementation available onBruce Schneier's website. Since I included blowfish.c & blowfish.h in my workspace, my compiler is running crazy. Like if it did not recognize Objective-c code, pointing...
Most likely, what is happening is that the compilation of blowfish.c is using your previously established precompiled header (.pch) file, and that is including an Objective-C framework. Just disable the precompiled header and you should be OK. You might be able to conditionalize those frameworks, but personally, I fin...
``` #define f(g,g2) g##g2 main() { int var12=100; printf("%d",f(var,12)); } ``` This code gives output 100, but if the preprocessor is implemented,printfwill be rewritten as: ``` printf("%d",var##12); ``` Then, how the output came?
The double hash##is atoken pasting operatorof the preprocessor. Theprintfwill be re-written like this: ``` printf("%d",var12); // No double-hash ``` The double-number-sign or "token-pasting" operator (##), which is sometimes called the "merging" operator, is used in both object-like and function-like macros. It perm...
This is my makefile: ``` program : program.o gcc -o program program.o program.o : program.c library.h gcc -c program.c ``` In "library.h" I've got the headers, but I have a problem with the semaphores. It says "undefined reference to sem_open , sem_post, sem_wait. . ."
You need to link to the pthread library -libpthread. Try changing your link command to ``` program : program.o gcc -pthread -o program program.o ```
I'm searching for a way to modify the file permissions of a file in Windows 7 using C. For example: I would like to add read permissions for C:\a.txt for the user A, or remove write permissions from user B. I have found some functions that are used in linux (Like chmod) but these are no good in windows. I'm sure a W...
It's been a while ago and, initially, not a pleasant experience, but then I found ATL Security: atlsecurity.h simplifies a lot the work with this stuff.http://msdn.microsoft.com/en-us/library/awt7k7f5(v=vs.80).aspx
What is the difference between the following in C language: ``` typedef enum month_t { jan, feb, march }month; ``` AND ``` typedef enum { monday, tuesday, wednesday }day; ``` Before posting this question I read this :What is a typedef enum in Objective-C? But did not understand quite well...
The first also introduces an enum tag, which means the enumeration can be used like this: ``` enum month_t first = jan; /* or */ month second = feb; ``` the second doesn't, so the enumeration is only available with thetypedef:ed nameday. Also, of course, the enumerations themselves are different, but that's kind of...
I'm trying to optimize some of my code in C, which is a lot bigger than the snippet below. Coming from Python, I wonder whether you can simply multiply an entire array by a number like I do below. Evidently, it does not work the way I do it below. Is there any other way that achieves the same thing, or do I have to s...
There is no short-cut you have to step through each element of the array. Note however that in your example, you may achieve a speedup by usingintrather thanfloatfor both your data and multiplier.
I want to use libev to listen for keyboard (keystrokes) events in the terminal. My idea is to use (n)curses getch() and set notimeout() (to be nonblocking) to tell getch() not to wait for next keypress. Is there a file descriptor that getch uses I can watch?
If you useinitscr(), the file descriptor you ask for isfileno(stdin), since the initscr subroutine is equivalent to: ``` newterm(getenv("TERM"), stdout, stdin); return stdscr; ``` If you usenewterm(type, outfile, infile), the file descriptor isfileno(infile).
So I was playing around with increments in C and I ran this code ``` int main() { int a = 3; int b = 8; b = a++; printf("%d %d",a, b); return 1; ``` } Originally I thought, oh yeah that's easy... So I thought it would print out 3 and 3. This is because a++ is a post increment, and increments the value ...
Thepostincrement is post (after) its use, not after theprintf(). It's changed before you reach yourprintf()call.
Is there any SSE2 instruction to convert a 8x16 register to two 4x32 registers,one 4x32 register having the odd indexed elements from the 8x16 register and the other having the even indexed elements? Please suggest.
Untested: ``` movdqa xmm1, xmm0 pslld xmm0, 16 psrad xmm1, 16 ; odd words psrad xmm0, 16 ; even words ``` Should be easy enough to convert to intrinsics. There is no single instruction for this, not even in later versions of SSE. Multiple-outputs is very rare, mostly reserved for old instructions. pmovsxwdfrom S...
If I try to print afloatas anint, this code: ``` main () { float a = 6.8f; printf("%d", a); } ``` prints 1073741824, while this code: ``` main () { float a = 9.5f; printf("%d", a); } ``` prints 0...
Not only the output, but the entire program has undefined behavior, since type of the value you are passing toprintf()does not match the type the format string expects.
I was wondering, I am writing a program in C, and I writing the output from my program to a csv file. This works locally, and I can create and update the file with no errors. But on the server, where I need to store the file - I do not have permissions to write to that file/directory. Is there a work around for get...
Well, you can run your program as a more authorative user, such as root. There is no simple way from the program itself to just ignore the operating system's security model, that would make it quite pointless. Note that if you're not the administrator on the server, you're likely not even allowed to run programs as ...
Is it possible to set the fields of a TCP header from a user program? The man page for tcp(7) does not list any fields which can be controlled using setsockopt(2). For IP, we can control the MTU, TTL fields using the setsockopt(2). ``` int sockfd = socket (AF_INET, SOCK_STREAM, 0); /* set the TCP fields now */ ... ...
Yes you can use raw sockets to set the TCP/UDP headers from a user program int fd = socket (PF_INET, SOCK_RAW, IPPROTO_TCP); More info on the linkhttp://csis.bits-pilani.ac.in/faculty/dk_tyagi/Study_stuffs/raw.html Search for RAW sockets and you will find more One more good reference is the Unix network programmi...
I have the following lines of code : ``` #define PORT 9987 ``` and ``` char *ptr = (char *)&PORT; ``` This seems to work in my server code. But as I wrote it in my client code, it gives this error message : ``` lvalue required as unary ‘&’ operand ``` What am I doing wrong?
C preprocessor is at play here. After the code is preprocessed, this how it looks like. ``` char *ptr = (char *)&9987; ``` address of (&) operator can be applied to a variable and not a literal.
Why doesGetOverlappedResultneed a file handle? It seems likeWaitForSingleObject(overlapped->hEvent)should be enough to wait on the event so that the overlapped I/O finishes, so what doesGetOverlappedResultuse the file handle for?
The remarks section of thedocumentationappears to explain whenhFileis needed: If the hEvent member of the OVERLAPPED structure is NULL, the system uses the state of the hFile handle to signal when the operation has been completed. Use of file, named pipe, or communications-device handles for this purpose is discourag...
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
You can cross the street without looking both ways many times and you might not get hit by a car. That doesn't mean it's a good idea.
``` #define f(g,g2) g##g2 main() { int var12=100; printf("%d",f(var,12)); } ``` This code gives output 100, but if the preprocessor is implemented,printfwill be rewritten as: ``` printf("%d",var##12); ``` Then, how the output came?
The double hash##is atoken pasting operatorof the preprocessor. Theprintfwill be re-written like this: ``` printf("%d",var12); // No double-hash ``` The double-number-sign or "token-pasting" operator (##), which is sometimes called the "merging" operator, is used in both object-like and function-like macros. It perm...
This is my makefile: ``` program : program.o gcc -o program program.o program.o : program.c library.h gcc -c program.c ``` In "library.h" I've got the headers, but I have a problem with the semaphores. It says "undefined reference to sem_open , sem_post, sem_wait. . ."
You need to link to the pthread library -libpthread. Try changing your link command to ``` program : program.o gcc -pthread -o program program.o ```
I'm searching for a way to modify the file permissions of a file in Windows 7 using C. For example: I would like to add read permissions for C:\a.txt for the user A, or remove write permissions from user B. I have found some functions that are used in linux (Like chmod) but these are no good in windows. I'm sure a W...
It's been a while ago and, initially, not a pleasant experience, but then I found ATL Security: atlsecurity.h simplifies a lot the work with this stuff.http://msdn.microsoft.com/en-us/library/awt7k7f5(v=vs.80).aspx
What is the difference between the following in C language: ``` typedef enum month_t { jan, feb, march }month; ``` AND ``` typedef enum { monday, tuesday, wednesday }day; ``` Before posting this question I read this :What is a typedef enum in Objective-C? But did not understand quite well...
The first also introduces an enum tag, which means the enumeration can be used like this: ``` enum month_t first = jan; /* or */ month second = feb; ``` the second doesn't, so the enumeration is only available with thetypedef:ed nameday. Also, of course, the enumerations themselves are different, but that's kind of...
I'm trying to optimize some of my code in C, which is a lot bigger than the snippet below. Coming from Python, I wonder whether you can simply multiply an entire array by a number like I do below. Evidently, it does not work the way I do it below. Is there any other way that achieves the same thing, or do I have to s...
There is no short-cut you have to step through each element of the array. Note however that in your example, you may achieve a speedup by usingintrather thanfloatfor both your data and multiplier.
I want to use libev to listen for keyboard (keystrokes) events in the terminal. My idea is to use (n)curses getch() and set notimeout() (to be nonblocking) to tell getch() not to wait for next keypress. Is there a file descriptor that getch uses I can watch?
If you useinitscr(), the file descriptor you ask for isfileno(stdin), since the initscr subroutine is equivalent to: ``` newterm(getenv("TERM"), stdout, stdin); return stdscr; ``` If you usenewterm(type, outfile, infile), the file descriptor isfileno(infile).
So I was playing around with increments in C and I ran this code ``` int main() { int a = 3; int b = 8; b = a++; printf("%d %d",a, b); return 1; ``` } Originally I thought, oh yeah that's easy... So I thought it would print out 3 and 3. This is because a++ is a post increment, and increments the value ...
Thepostincrement is post (after) its use, not after theprintf(). It's changed before you reach yourprintf()call.
Is there any SSE2 instruction to convert a 8x16 register to two 4x32 registers,one 4x32 register having the odd indexed elements from the 8x16 register and the other having the even indexed elements? Please suggest.
Untested: ``` movdqa xmm1, xmm0 pslld xmm0, 16 psrad xmm1, 16 ; odd words psrad xmm0, 16 ; even words ``` Should be easy enough to convert to intrinsics. There is no single instruction for this, not even in later versions of SSE. Multiple-outputs is very rare, mostly reserved for old instructions. pmovsxwdfrom S...
If I try to print afloatas anint, this code: ``` main () { float a = 6.8f; printf("%d", a); } ``` prints 1073741824, while this code: ``` main () { float a = 9.5f; printf("%d", a); } ``` prints 0...
Not only the output, but the entire program has undefined behavior, since type of the value you are passing toprintf()does not match the type the format string expects.
I was wondering, I am writing a program in C, and I writing the output from my program to a csv file. This works locally, and I can create and update the file with no errors. But on the server, where I need to store the file - I do not have permissions to write to that file/directory. Is there a work around for get...
Well, you can run your program as a more authorative user, such as root. There is no simple way from the program itself to just ignore the operating system's security model, that would make it quite pointless. Note that if you're not the administrator on the server, you're likely not even allowed to run programs as ...
Is it possible to set the fields of a TCP header from a user program? The man page for tcp(7) does not list any fields which can be controlled using setsockopt(2). For IP, we can control the MTU, TTL fields using the setsockopt(2). ``` int sockfd = socket (AF_INET, SOCK_STREAM, 0); /* set the TCP fields now */ ... ...
Yes you can use raw sockets to set the TCP/UDP headers from a user program int fd = socket (PF_INET, SOCK_RAW, IPPROTO_TCP); More info on the linkhttp://csis.bits-pilani.ac.in/faculty/dk_tyagi/Study_stuffs/raw.html Search for RAW sockets and you will find more One more good reference is the Unix network programmi...
Considering the following definition: ``` struct { int x; int y; } point; void main() { ... } ``` You're declaring the variable "point" of "anonymous struct" type, is there any way to declare another variable of the same type outside the struct definition (maybe in main function)?
No, there isn't, at least not in standard C. If you want to use the type, you have to give it a name.
Today, I have just noticed a statement in a C struct, and to be honest I was like WTF at first. It is like; ``` struct foo { void *private; //Some other members }; ``` Believe or not this struct is being compiled without any error. So what is the purpose of adding such a line (void *private)?
In pure C there's noprivatekeyword, so the above is perfectly legal, albeit a very bad idea. This would be invalid C++ though, and a C++ compiler would surely yield an error.
Suppose you have array arr[N] of increasing numbers. You have to divide it in two other (Left and Right): ``` L = {0, 2, 4, 6, 8, 10, ...} R = {1, 3, 5, 7, 9, 11, ...} ``` The following algorithm does this: ``` for ( i = 0; i < (N / 2) ; i++ ) { L[i] = arr[2 * i + 0]; R[i] = arr[2 * i + 1]; ...
The easy solution is just to literally reverse your existing operation: ``` for (i = 0; i < (N / 2); i++) { arr[2 * i + 0] = L[i]; arr[2 * i + 1] = R[i]; } ```