question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
i am trying to make a server client application using sockets in C.
Server and client compile just fine but they dont seem to connect with each other and i don't understand why (i just started learning about sockets).
My OS is SunOs 5.10.
This is my code for the server :http://pastebin.com/TbLCG5BA
This is my code f... |
In both your client and your server you're calling bzero() on your structuresafteryou initialize them. That means you first fill in your information, and then you set everything to zero (losing all your information).
Set everything to zero first (thus correctly initializing fields you won't use). Then initialize your... |
I am getting this error:
```
cannot convert parameter 2 from 'const char [14]' to 'LPCWSTR'
```
With the code below. It is supposed to be C but at best visual studio 2012 offers an empty c++ project:
```
#include "windows.h"
int WINAPI WinMain (HINSTANCE hinst, HINSTANCE hprevinst, LPSTR cmdline, int showcmd)
{
... |
It seems your current settings are set up so that WinAPI functions expect wide strings:
```
MessageBox(NULL, L"Merhaba Dunya", L"Merhaba", MB_OK);
```
|
I have a C functionuint8_t command_read(const FILE* const in)that reads fromin. I would like to write a unit test for the function. Is it possible to create aFILE*in memory for the test since I would like to avoid having to interact with the filesystem? If not, what are the alternatives?
|
Is it possible to create a FILE* in memory for the test?
Sure. For writing:
```
char *buf;
size_t sz;
FILE *f = open_memstream(&buf, &sz);
// do stuff with `f`
fclose(f);
// here you can access the contents of `f` using `buf` and `sz`
free(buf); // when done
```
This is POSIX.Docs.
For reading:
```
char buf[] ... |
I need to store an user entry twice.
For example:
```
for (conta_vetor=0;conta_vetor<50;conta_vetor++)
{
printf("Digite o %d número:\n",conta_vetor);
scanf("%d", &vetor[conta_vetor]);
}
```
The user entry must be stored on the vector position and on a new adress, using the same scanf.
How can i do that?
|
From your comments:
```
int x;
int conta_vetor = 0;
for (;;)
{
printf("Digite o %d número:\n",conta_vetor);
scanf("%d", &x);
if (x != -1)
vetor[conta_vetor++] = x;
else
break;
}
```
|
Can you help me to find the main (only) thread ID of a given by ID process, please ?
Task context:
A running process has (at the moment) no windows but a(some) thread(s).
Wanted:
Posting ofWM_QUITat the main thread only.
Not-wanted:
Using ofTerminateProcessor postingWM_QUITat the non-primary threads.
|
A much simpler and surer way to get the thread id of the main thread is to let the main thread records its own thread id using::GetCurrentThreadId()into a shared global variable, perhaps in your WinMain or somewhere at the very beginning of your 'main thread':
```
MainThreadId_G = ::GetCurrentThreadId();
```
then in... |
In my application, written in C, under Windows-XP:
how can I check if a file is already open by another application?
One option is to rename the file, and to check if it was renamed.
Another option is to open the file for appending.
But these options are very time-consuming.
Is there any other, less time-consuming so... |
No function exists in the Windows API that will check if a function is open in another application. If it did exist it would be subject to a race condition.
Suppose that you checked first whether or not a file was already opened and the answer came back that it was not currently open. Then you move on to open it, but... |
i am trying to make a server client application using sockets in C.
Server and client compile just fine but they dont seem to connect with each other and i don't understand why (i just started learning about sockets).
My OS is SunOs 5.10.
This is my code for the server :http://pastebin.com/TbLCG5BA
This is my code f... |
In both your client and your server you're calling bzero() on your structuresafteryou initialize them. That means you first fill in your information, and then you set everything to zero (losing all your information).
Set everything to zero first (thus correctly initializing fields you won't use). Then initialize your... |
I am getting this error:
```
cannot convert parameter 2 from 'const char [14]' to 'LPCWSTR'
```
With the code below. It is supposed to be C but at best visual studio 2012 offers an empty c++ project:
```
#include "windows.h"
int WINAPI WinMain (HINSTANCE hinst, HINSTANCE hprevinst, LPSTR cmdline, int showcmd)
{
... |
It seems your current settings are set up so that WinAPI functions expect wide strings:
```
MessageBox(NULL, L"Merhaba Dunya", L"Merhaba", MB_OK);
```
|
I have a C functionuint8_t command_read(const FILE* const in)that reads fromin. I would like to write a unit test for the function. Is it possible to create aFILE*in memory for the test since I would like to avoid having to interact with the filesystem? If not, what are the alternatives?
|
Is it possible to create a FILE* in memory for the test?
Sure. For writing:
```
char *buf;
size_t sz;
FILE *f = open_memstream(&buf, &sz);
// do stuff with `f`
fclose(f);
// here you can access the contents of `f` using `buf` and `sz`
free(buf); // when done
```
This is POSIX.Docs.
For reading:
```
char buf[] ... |
I need to store an user entry twice.
For example:
```
for (conta_vetor=0;conta_vetor<50;conta_vetor++)
{
printf("Digite o %d número:\n",conta_vetor);
scanf("%d", &vetor[conta_vetor]);
}
```
The user entry must be stored on the vector position and on a new adress, using the same scanf.
How can i do that?
|
From your comments:
```
int x;
int conta_vetor = 0;
for (;;)
{
printf("Digite o %d número:\n",conta_vetor);
scanf("%d", &x);
if (x != -1)
vetor[conta_vetor++] = x;
else
break;
}
```
|
consider the the two functions :
```
int add1(int x,int y)
{
return x+y;
}
void add2(int x,int y,int *sum)
{
*sum=x+y;
}
```
I generally use functions of the form add1 but I found some codes using functions of the form add2.Even if the size return value is large(like an array or struct) we can just return its pont... |
There's also the reason of returning success state.
There are a lot of functions like:
```
bool f(int arg1, int arg2, int *ret)
{
}
```
Wherebool(orenum) return the success of the function. Instead of checkingif ret is null...(And if you had more than 1 variable).
|
This is a code to return a reversed String like "ABC" returns "CBA", but it returns this "CBA═²²²²ß♣Y*&s".
What is wrong?
```
char* inv(char* C)
{
int lenght = strLenght(C)-1;
int idx=0;
char* tempStr = (char*)malloc(lenght+2);
for (;lenght>=0;lenght--,idx++)
{
tempStr[idx] = C[lenght];
... |
YourtempStrisn't null terminated. Alsostrlen()is a integrated function in c you don't have to write your own.
|
How to play a sound file specified by user in an array using the PlaySound()? I'm using Windows7 and VC++ 2010.
Suppose I use thegets(song);statement to input the complete path of the song from user.
|
http://msdn.microsoft.com/en-us/library/windows/desktop/dd743680(v=vs.85).aspx
```
PlaySound( song, NULL, SND_FILENAME );
```
|
I have a log file I want to parse
I only need the first two fields (separated by space)
sample line from the log file:
```
1362960460.697 19 27.197.12.76 TCP_MISS/404 339 GET http://what-ever-server.com/what-ever-file - DIRECT/22.22.22.22 text/html
```
The first field should be without the numbers after the "."
I... |
This is what awk is for.
```
cat logfile | awk '{print $1 " " $2}' | sed 's_\.[0-9]*__g'
```
You print the first and second fields of each line withawk. Then you match the decimal places and remove them usingsed.
|
va_arg(a,type)macro expands to__builtin_va_arg(a,type)which is built-in part of compiler.
Is it possible to implement type based functionality, if yes how?
|
Notice thatva_argcannot determine the actual type of the
argument passed to the function, but uses whatever type is passed as
the type macro argument as its type.
Lets see howva_argworks, one possibility fromhere, is
```
#define va_arg(ap,t) (*(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)))
```
First of all, it's... |
This question already has answers here:C conditional operator ('?') with empty second parameter [duplicate](6 answers)Closed10 years ago.
I am currently porting some Unix code to Windows and came across a rather strange use of the conditional operator which is not valid syntax according to Visual Studio (either 2010 ... |
It's a gcc extension.
```
x = a ? : b;
```
isalmostthe same as
```
x = a ? a : b;
```
except for the fact thatais only evaluatedonce, which is useful ifahas any side effects or is expensive to evaluate.
|
Everything I've seen says to uselsof -p, but I'm looking for something that doesn't require a fork/exec.
For example on Linux one can simply walk/proc/{pid}/fd.
|
You canuseproc_pidinfowith thePROC_PIDLISTFDSoption to enumerate the files used by a given process. You can then useproc_pidfdinfoon each file in turn with thePROC_PIDFDVNODEPATHINFOoption to get its path.
|
Hey guys I'm getting a seg fault with strtok, just need a little bit of help!
```
char s[1024];
char *token[2];
while(fgets(s, sizeof(s), fp) != NULL) // Read line from file fp until end
{
token[0] = strtok(s, "\t\n");
token[1] = strtok(NULL, "\t\n");
token[2] = strtok(NULL, "\t\n");
printf("%d:%s:%d"... |
Array indexing problem.
You should declare the array of pointers as follows,
```
char *token[3];
```
|
I send from arduino to arduino string (I2C), catch and save to char[10]. When I compare this variable to text, condition don't have execute :-/ And I don't know why...
```
char dataRx[10] = "";
void DaemonReceiving(int howMany){
int index = 0;
while(Wire.available() > 0){
char c = Wire.read();
dataRx[i... |
To compare the dataRX string to "HELLO", use:
```
if (strcmp (dataRx,"HELLO") == 0) {
// matches HELLO
}
```
|
So I have a minimal OS that doesn't do much. There's a bootloader, that loads a basic C kernel in 32-bit protected mode. How do I port in a C library so I can use things likeprintf? I'm looking to use the GNU C Library. Are there any tutorials anywhere?
|
Ok, porting in a C library isn't that hard, i'm using Newlib in my kernel. Here is a tutorial to start:http://wiki.osdev.org/Porting_Newlib.
You basically need to:
Compile the library (for example Newlib) using your cross compilerProvide stub-implementations for a list of system functions (like fork, fstat, etc.) in... |
Everything I've seen says to uselsof -p, but I'm looking for something that doesn't require a fork/exec.
For example on Linux one can simply walk/proc/{pid}/fd.
|
You canuseproc_pidinfowith thePROC_PIDLISTFDSoption to enumerate the files used by a given process. You can then useproc_pidfdinfoon each file in turn with thePROC_PIDFDVNODEPATHINFOoption to get its path.
|
Hey guys I'm getting a seg fault with strtok, just need a little bit of help!
```
char s[1024];
char *token[2];
while(fgets(s, sizeof(s), fp) != NULL) // Read line from file fp until end
{
token[0] = strtok(s, "\t\n");
token[1] = strtok(NULL, "\t\n");
token[2] = strtok(NULL, "\t\n");
printf("%d:%s:%d"... |
Array indexing problem.
You should declare the array of pointers as follows,
```
char *token[3];
```
|
I send from arduino to arduino string (I2C), catch and save to char[10]. When I compare this variable to text, condition don't have execute :-/ And I don't know why...
```
char dataRx[10] = "";
void DaemonReceiving(int howMany){
int index = 0;
while(Wire.available() > 0){
char c = Wire.read();
dataRx[i... |
To compare the dataRX string to "HELLO", use:
```
if (strcmp (dataRx,"HELLO") == 0) {
// matches HELLO
}
```
|
So I have a minimal OS that doesn't do much. There's a bootloader, that loads a basic C kernel in 32-bit protected mode. How do I port in a C library so I can use things likeprintf? I'm looking to use the GNU C Library. Are there any tutorials anywhere?
|
Ok, porting in a C library isn't that hard, i'm using Newlib in my kernel. Here is a tutorial to start:http://wiki.osdev.org/Porting_Newlib.
You basically need to:
Compile the library (for example Newlib) using your cross compilerProvide stub-implementations for a list of system functions (like fork, fstat, etc.) in... |
This question already has answers here:C and Python - different behaviour of the modulo (%) operation [duplicate](6 answers)How does the modulo (%) operator work on negative numbers in Python?(12 answers)Why is operator% referred to as the "modulus" operator instead of the "remainder" operator?(3 answers)Closed10 year... |
Wikipediahas a nice table which shows the sign of the operation for various languages. In Python it is the sign of the divisor (26), in Java/C the sign of the dividend (-1).
|
I have a struct
```
typedef struct _scaffale {
int NumeroScaffale;
scaffali * succ;
copia** pos;
} scaffale;
```
in which I have an array of the struct copia. The error comes in the following code:
```
copia** temp;
temp=scaff->pos;
(temp+controllo)=nuovo->copie;
```
in the third row to be precise.... |
(temp+controllo)is an rvalue. By that I mean it's a computed value, not a location to put something. I'm guessing that what you really meant is*(temp+controllo) = nuovo->copie;instead, which would have assignednuovo->copieinto the location identified bytemp+controllo.
For an analogy, ifiis anint, you can sayi = 3, bu... |
What is the best way to execute this command: "sudo cat /var/log/auth.log | grep Accepted" inside my C program ?
I tried to use:
```
sprintf(command_result,"sudo cat /var/log/auth.log | grep Accepted");
```
But it didn't work obviously.
|
You cannot execute the command withsprintf()you needsystem()atleast
fix:
```
sprintf(command_result, "sudo cat /var/log/auth.log | grep Accepted");
system(command_result);
```
|
I have tried the following code:
File1.c:
```
int x;
```
File2.c:
```
extern char x;
main()
{
x=10;
....
....
}
```
and compiled as
$gcc File1.c File2.c
and I didn't get any error but I was expecting one.
|
InFile.c, you promise to the compiler thatxis of typechar. Since every translation unit is compiled separately, the compiler has no way of verifying this, and takes your word for it. And the linker doesn't do any type checking. You end up with an invalid program that builds with no errors.
This is why you should use ... |
I have a probably simple question, which I just cant seem to understand.
I am creating a serial parser for a datalogger which sends a serial stream. Under the documentation for the product a calculation is stated, which I don't understand.
```
Lateral = Data1 And 0x7F + Data2 / 0x100
If (Data1 And 0x80)=0 Then Later... |
Bitwise AND -- a bit in the output is set if and only if the corresponding bit is set inbothinputs.
Since your tags indicate that you're working in C, you can perform bitwise AND with the & operator.
(Note that 0x7F is 01111111 and 0x80 is 10000000 in binary, so ANDing with these correspond respectively to extractin... |
I want to print the output of each thread in a new window.
Where as the main function outputs to the first terminal.
My code is in c language.
Please help me.Thank you!
|
Short answer is: You can't.
Long answer is, you can but it's a lot of work. Basically you have to somehow open a window and attach a pseudo-terminal to it, but one without a shell.
A shorter solution would be to use processes instead of threads. Then you can split your program into two or more programs, one to creat... |
I'm trying to use sprintf to make a bunch of strings that represent file names. The files will be named 1, 2, 3, 4, 5, ... However when I do this I get some weird errors. The for loop only prints out the first round. The output is shown here: str: 1.xlxs i: 7567468
```
char str[3];
int i;
for(i = 0; i < FILES; ... |
Thestr[3]buffer is too small to hold the data ("1.xlxs"). It should be at leaststr[7]to hold the string and a null byte.
If the buffer is too small, you'll get a buffer overflow:
http://en.wikipedia.org/wiki/Stack_buffer_overflow
|
all:
Is there any good open source C library which provides sending email function? I don't want use mailx command in Solaris.Thanks very much in advance!
|
I just searched on google and found these few link..hope this will help.
http://sourceforge.net/projects/jwsmtp/?source=dlp
http://www.stafford.uklinux.net/libesmtp/download.html
|
Let I have below program. I would like to assign the value to the enum member at run time. How can i do it?
```
typedef enum test{
a, b
}test;
typedef struct abc{
test Test;
}abc;
int main(){
abc ab;
ab.Test.a = 5;//Throwing an error as "Expression must have class type"
return 0;
}
```
Please he... |
Anenumis just a way to give names to someconstants, for clarity reasons.
It can be useful because, contrary todefines, the names you set for your variables are (typically) not discarded by your compiler, hence you can see them while going through your program with a debugger.
If you want to regroup variables and set... |
I'm trying to get both the CN and emailAddress field from a X509 cert object in C. Currently i'm getting the CN like this:
```
cert_entry = X509_NAME_get_entry(X509_get_subject_name(cert), 0);
ASN1_STRING *entryData = X509_NAME_ENTRY_get_data( cert_entry );
ASN1_STRING_to_UTF8(&CN, entryData);
printf("%s",CN);
```
M... |
Figured it out
```
X509_NAME * subject_name = X509_get_subject_name(cert);
int nid_email = OBJ_txt2nid("emailAddress");
X509_NAME_get_text_by_NID(subject_name, nid_email, peer_email, 256);
```
|
Does anyone know how to turn an integer array into a float array?
|
Your question is not worded well; however, assuming you have already declared your integer array, you could try something like this:
```
// instantiate float array
float fArray[sizeOfIntArray];
// step through each element of integer array, and copy into float array as float
for(int i = 0; i < sizeOfIntArray;... |
My final executable (this is in unix though) will be proj07.
```
proj07: /user/cse320/Projects/project07.driver.o proj07.support.o
gcc -Wall /user/cse320/Projects/project07.driver.o proj07.support.o
proj07.support.o: proj07.support.c
gcc -c proj07.support.c
```
This creates proj07.support.o but no proj07 e... |
You probably do have ana.outexecutable. Add-o $@to your firstgccoccurrence and you should be fine.
|
This is a very trivial problem:
There are four boolean functions: a(), b(), c() and d(). I want to keep calling them in order until the first one returnstrue. instead of doing the traditional
```
if(!a()) {
if(!b()) {
if(!c()) {
d();
}
}
}
```
or
```
if(!a() && !b() && !c()) d();... |
The code you have written is valid.d()will only be evaluated if other boolean functions returnfalse.
However the short-circuited evaluation is less readable, and error prone from a maintenance point of view, because a reader might not get understand it trivially.
|
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed10 years ago.Improve this question
I just finished writing a c program that split a very large program into its different components and stored them in a tre... |
You can try WinDirStat, it does pretty much what you ask for.
http://windirstat.info/
There is also a version for linux
http://kdirstat.sourceforge.net/
|
I am aware that the above mentioned are used to round off the float values and double values. But can someone please explain how each one rounds off the values? I couldn't find any documentation for this.
|
See the manual pages (learn to Google for "man WHATEVER" when WHATEVER is a library function):
lroundf()- round to nearest integer, away from zerofloor()- largest integral value not greater than argumentnearbyintf()- round to integral value in floating-point format
|
How to get a process name from his pid ?
For example I execute cat file1.txt, but I want to figure out that cat command and its arguments since its pid in the system. Is there a struct to determine it or something similar? Any idea?
|
There is not any general way to do this unix.Each OS has different ways to handle it and some are very hard. You mention Linux though. With Linux, the info is in the /proc filesystem.To get the command line for process id 9999, read the file/proc/9999/cmdline.
|
After creating a process and waiting for it to finish, does it's STARTUPINFO still available or is it destroyed ?
```
STARTUPINFO si;
bRes = CreateProcess(NULL, command, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);
dwRes = WaitForSingleObject(pi.hProcess, INFINITE);
```
After this does thesigets modified/destroyed ... |
Windows creates a copy of the startup info struct for the new process. That has to happen because the new process has a brand new address space and cannot see your struct.
Now, what happens to your struct? Well, thedocumentationhas the answer. The parameter is annotated like this:
```
_In_ LPSTARTUPINFO lpStartupInf... |
I see two possible implementations for a MAX macro in C. Which of these would be best?
define MAX(X,Y) ((X) < (Y) ? : (Y) : (X))define MAX(X,Y) 0.5*(X+Y+ABS(X-Y))
|
Second one is hard to read, and actually broken. Really bad idea.
Second one always uses doubles. You will get rounding errors. I certainly wouldn't expect getting a result that's not equal to either side.When applied to integers it returns a double, quite surprising. Floats get promoted to double as well.If you "fix... |
In my function, I need to read some data from a file into a buffer, manipulate the data and write it back to another file. The file is of unknown size and may be very large.
If I use a small buffer, there will be a long read/write cycle and it would take much time. In contrast, long buffer means I need to consume mor... |
See what Microsoft has to say about IO size:http://technet.microsoft.com/en-us/library/cc938632.aspx. Basically, they say you should probably do IO in 64K blocks.
On *NIX platforms,struct stathas ast_blksizemember which says what should be a minimal IO block size.
|
I know that lots of CL commands are available in C ILE but it's often very hard to find the C function name corresponding to the CL command.
Do you know a website who reference all these ILE C function ?
Do you know the ILE C function corresponding to the CL command :
CHGJOB INQMSGRPY(*DFT)
Of course I've tried to s... |
I don't have experience calling APIs from C, but I think you're looking for the QWTCHGJB API.
Here's IBM's QWTCHGJB API documentation for V5R4.
Here's a code example that demonstrates a call to this API.
You can use the API finder to search for this sort of info.
(Note that you should seek out the appropriate docu... |
I need to be able to use fork() for a small project. The thing is that the example code is not working:
```
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
pid_t pID = fork();
if (pID == 0) // child
{
printf("CHILD\n");
// Code only executed... |
On Windows you can't usefork(). UseCreateProcess()/CreateProcessEx()instead.
|
I have come across this question in a programming contest, but couldn't find the answer can anyone please help me with this???
```
Input<<string
Output<<reverse(string)
```
constraints: No loops allowed,No inbuilt functions have to be used!
|
Use recursion:
```
#include <stdio.h>
void print_reversed(const char* str) {
if (*str) {
print_reversed(str + 1);
printf("%c", *str);
}
}
int main() {
print_reversed("abcdef");
printf("\n");
}
```
|
```
int parse_command_line (char commandLine[MAX_INPUT_LINE_LENGTH], char* cmds[MAX_CMDS_NUM]){
char delims[] = "|";
char *result = NULL;
result = strtok( commandLine, delims );
int count = 0;
if((logfp=fopen("LOGFILE", "w"))==NULL)
{
perror("Error");
exit(1);
while( result != NULL ) {
... |
To do, just add
```
cmds[count] = result;
```
after thefprintf()and beforecount=count+1;
|
Is there any functional difference between logical and bitwise operators in the following code? What are the reasons to use one or another?
```
typedef unsigned char BOOLEAN;
void orOperatorsComparison(BOOLEAN bBar, BOOLEAN bFoo)
{
BOOLEAN bLogicalOr = (bFoo || bBar);
BOOLEAN bBitwiseOr = (bFoo | bBar);
... ... |
What does "support" mean?
If it's a logical or that you mean, then of course you should always use||since that is the Boolean, logical, "or" operator.
It has the benefit of being able to short-circuit, but that won't matter much in code this simple.
I would consider it odd and weird (and due for correcting) if bitw... |
When I compile this code, it gives me
"[Error] unknown type name 'days' ". What am I doing wrong?
```
#include <stdio.h>
int main(void){
int k=0;
enum days {Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday};
days dayVariable;
printf("Enter number of the day: ");
scanf("%d",&k);
dayVariable=days(k);
pri... |
If it's C, you must write:
```
enum days dayVariable;
...
dayVariable = (enum days)k;
```
If you wantdaysto be the type name, typedef it:
```
typedef enum {Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday} days;
```
Other than that, you use the wrong format specifier in printf.
P.S.
And remember, C and... |
I was just wondering if there is some macro-hack we can use, to alter existing printf() statements in a project.
```
/* file.c */
printf ("%s", strerror(errno));
/* After macro processing, this line would become */
printf ("%s %s %d", strerror(errno), __FILE__, __LINE__);
```
|
With the caveat in my comment, you could do it using avariadic macro:
```
#define PRINTF_FL(format, ...) \
printf(format " %s %d", __VA_ARGS__, __FILE__, __LINE__)
```
|
How does Visual Studio know if a project is C or C++? Is there any configuration or build parameter that indicates this ?
Does VS use C compiler for C, and C++ compiler for C++ ?
|
Does VS use C compiler for C, and C++ compiler for C++ ?
No
theclcompiler is smart enough to know(based on file extension) if a file is a.cppor.ccfile - which it considers as C++ file. And theclcompiler will consider a.cfile as a C program source file, and compile accordingly. Although it does load a separatedllfile... |
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed10 years ago.Improve this question
I just finished writing a c program that split a very large program into its different components and stored them in a tre... |
You can try WinDirStat, it does pretty much what you ask for.
http://windirstat.info/
There is also a version for linux
http://kdirstat.sourceforge.net/
|
I am aware that the above mentioned are used to round off the float values and double values. But can someone please explain how each one rounds off the values? I couldn't find any documentation for this.
|
See the manual pages (learn to Google for "man WHATEVER" when WHATEVER is a library function):
lroundf()- round to nearest integer, away from zerofloor()- largest integral value not greater than argumentnearbyintf()- round to integral value in floating-point format
|
How to get a process name from his pid ?
For example I execute cat file1.txt, but I want to figure out that cat command and its arguments since its pid in the system. Is there a struct to determine it or something similar? Any idea?
|
There is not any general way to do this unix.Each OS has different ways to handle it and some are very hard. You mention Linux though. With Linux, the info is in the /proc filesystem.To get the command line for process id 9999, read the file/proc/9999/cmdline.
|
After creating a process and waiting for it to finish, does it's STARTUPINFO still available or is it destroyed ?
```
STARTUPINFO si;
bRes = CreateProcess(NULL, command, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);
dwRes = WaitForSingleObject(pi.hProcess, INFINITE);
```
After this does thesigets modified/destroyed ... |
Windows creates a copy of the startup info struct for the new process. That has to happen because the new process has a brand new address space and cannot see your struct.
Now, what happens to your struct? Well, thedocumentationhas the answer. The parameter is annotated like this:
```
_In_ LPSTARTUPINFO lpStartupInf... |
I am trying to develop a simple command-line client to the server. After I connect to the server and setup everything correctly I want to redirectSTDINto the socket connected to the server and the same socket toSTDOUT. I want to achieve behavior similar to the ofnctool.
The most simple solution would be useselect()an... |
On Linux you can usesplice(2)to move data between file descriptors at the kernel level. Though, you would still have to useselect(2)(or equivalent) to handle the two directions in parallel or alternatively use two threads.
|
Good practice aside, I'm attempting to make coding just a tad easier for myself.
Is it possible to make a header file to handle myriad inclusions so that a source can just include the one header?
Edit: Some of you are referencing Cocoa. I forgot to mention C/C++ programming. It's in the tags, but I forgot to put ... |
Sure it is possible, but I wouldn't call that a good programming style.
You're going to increase source code dependencies, you won't be able to recompile a part of your project without recompiling everything, and you will lose track of what depends on what.
Personally, I would say don't do it.
|
In the kernel space I want to copy a character from the terminal and put it in a user space.
I am trying this code, but it's not working:
```
char mychar;
int result;
mychar = getch();
result = copyout(&mychar, chptr, sizeof(mychr));
```
(chptris a pointer to the user level space)
copyoutis not returning 1. Does a... |
Assuming a BSD-ishcopyout:
```
RETURN VALUES
The copy functions return 0 on success or EFAULT if a bad address is
encountered. ...
```
In other words, you're just expecting something other than what it returns. :-)
|
This question already has answers here:How can I convert an integer to a hexadecimal string in C?(7 answers)Closed10 years ago.
I have a pointer which point to a memory of 20 bytes, and then copy something to the memory
```
u_char* pkt=malloc(20);
memcpy(pkt, somecontent, 20);
```
I want to examine the 20 bytes sta... |
Tryprintf:
```
int i=0;
for (; i<20; i++)
printf("0x%.2x ", pkt[i]);
printf("\n");
```
|
I'm writing finite-difference method program using C. The stiffness matrix is symmetrical and band. For its storage I'd like to use Sparse Diagonal Storage format.
Could someone tell please, what solvers can use diagonal storage format? Intel MKL's Paradiso uses only CRS-format, SparseLib doesn't have, Spooles seems ... |
The sparse libraries concentrate on general purpose sparse storage. For banded matrices you can use any of the standard linear algebra libraries, for example LAPACK.
|
I have a application in C programming which uses jansson library(json library written in C). I'm trying to view value of json_t object in gdb but it just prints
```
(gdb) p jmsg
$20 = (json_t *) 0x69c350
(gdb) p *jmsg
$21 = {type = JSON_OBJECT, refcount = 1}
```
How is it possible to view the value of json_t in gdb.... |
When in GDB, you can make function calls directly. Jansson library has a json_dumps(json_t *, int flags) API that returns a char* string of the json_t object.
So while in GDB, just simply do:
```
(gdb) call json_dumps(obj, 0)
```
GDB will then print the string output of your json object.
|
I am trying to accomplish the following using nested for loops (C language):
```
a[0] = b[0][0];
a[1] = b[1][0];
a[2] = b[1][1];
a[3] = b[2][0];
a[4] = b[2][1];
a[5] = b[2][2];
a[6] = b[3][0];
a[7] = b[3][1];
a[8] = b[3][2];
a[9] = b[3][3];
```
I have this:
```
for (j=0; j<3; ++j... |
Two fixes.
include a countermake your bound check inclusive
Illustrated:
```
int i=0;
for (j = 0; j <= 3; ++j)
for (k = 0; k <= j; ++k)
a[i++] = b[j][k];
```
Ideone
|
I have a problem with debugging a process on arm + Linux platform:
This is a daemon process working with CAPWAP protocol, so it continuously communicates with another remote process. When it crashes with a segmentation fault, my usual means of debugging is to add some log output viaprintf, to find where the process h... |
You could also enablecore(5)dump, then usegdbpost-mortem on that core with
```
gdb yourprogram core
```
To enable core dump, you need to call thesetrlimit(2)syscall withRLIMIT_CORE, usually in some parent process (e.g. the shell withulimit)
BTW, you could also start your program thrugdbusing
```
gdb --args yourpro... |
I was trying to implementgetchar()function usingreadfunction in unistd.h.
I knowread(0,buffer,1)is equivalent togetchar(), however, it takes too many system calls.
Is there a way to implementgetchar()function using less system calls?
|
Yes -- read a larger buffer (e.g., at least a few kilobytes) full of data. When the user calls getchar, return a char from the buffer unless it's empty. If it is empty, refill the buffer first, then return a char.
|
Currently, I have some confusion in realloc an array string. If I have this:
```
char** str = (char**)malloc(100*sizeof(char*));
str[0] = (char*)malloc(sizeof(char)*7); //allocate a space for string size 7
//some other code that make the array full
```
My question is, if I want to reallocstr[0]to size8, do I need to... |
Youreallocthe master array when you want to add a string (changing thenumber of strings). Youreallocan individual string when you want to change thatstring's length.
Therefore, onlyreallocstr[0]if you want to change the string's buffer size.
|
A weird behaviour when I shell:
```
bush@ubuntu:~/CPPWorkspace/Ex12$ gcc users/dubi/justPrnit.C
```
Returns an error:
```
gcc: error trying to exec 'cc1plus': execvp: No such file or directory
```
But when I change justPrnit.C to justPrnit.c (with little 'c') it compiled successfully.
What's that?
|
error trying to exec 'cc1plus'
Because.Cis assumed to be a C++ source file (cc1plusis the C++ parser backend of GCC - by the way, it seems that your local installation of GCC lacksg++- are you using the default [incomplete] setup?).
To solve this, use the-xswitch to force the language:
```
gcc -x c users/dubi/justP... |
I am having trouble reading from stdin constantly until CTRL+D is pressed. I have to useread()from unistd.h. I am trying to simulate the cat function. Is there a way to make my buffer (which I print with %s) to look neat without the unnecessary spaces fromread(STDIN_FILENO, buf, 256)?
|
I am trying to simulate the cat function.
Here is a start:
```
ssize_t nread, nwrite;
while ((nread = read(STDIN_FILENO, buf, sizeof buf)) > 0) {
nwrite = write(STDOUT_FILENO, buf, nread);
/* Error handling and partial writes left as exercise. */
}
```
|
According to theOpenGroup, if open() is called with O_CREAT and the file does not already exist, it will be created with the file permission specified as the third argument in the function:
the file shall be created; the user ID of the file shall be set to the
effective user ID of the process; the group ID of the f... |
From thefopen(3)man page:
Any created files will have modeS_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH (0666), as modified by the process's umask value (see umask(2)).
Soumask(2)is your friend.
|
I'm writing a character device file and would like to know if there's any way to have a section of data for each instance of a device file. I've been looking at the inode and file structures for a place to store a non-volatile pointer, but have had no luck. can you do this with character device files, or should I be c... |
You cannot store data in a device file. The whole point of a device file is that the data you write to it is passed to some driver.
You could theoretically store information in the file name, or in the group id field of the inode, but that would beveryweird.
Your best solution is most likely to store your data separ... |
I have looked all over, and was shocked to be unable to find anything on the topic.
I just want to be able to capture events from a simple mouse scrollwheel.
|
Yep, this is incredibly confusing. That's because X11 decided to assign mouse scroll wheel events as mouse button 4 and 5. Receiving scrollwheel events is the same as receiving mouse button press events (ButtonPress events according to /usr/include/X11/X.h). Note also that the header file defines Button1..Button5. But... |
What is the syntax in order to pass an array that is not predefined in a function as operand?
For example, I have this function:
```
void kilos(int percentage[2], char liquid[2][4]);
```
So if I make two different arrays and pass them as operands everything work properly.
How can this work if I do not want to make ... |
In C++, if you have a C++11 capable compiler and you usestd::vectorinstead of raw arrays, you could useinitializer lists:
```
void kilos(const std::vector<int> percentage,
const std::vector<std::string> liquid);
// ...
kilos({40, 60}, {"water", "milk"});
```
|
I've read somewhere, that it's good to have eachtypedefin separate file, but it wasn't even explained.
For example like this:
```
#ifndef _MYTYPEDEF_H
#define _MYTYPEDEF_H
#pragma once
#include <iostream>
typedef std::pair<unsigned short, int> my_typedef;
#endif //_MYTYPEDEF_H
```
But I think it will be a mess ... |
This only obfuscates the code and confuses the one who maintains(which is not usually the one who invents such fancy ideas) it.This is only good(if at all) for the developer who only sees single TUs during development but not for the one who maintains it and sees the entire code base post development.Please don't do i... |
I'm training with file management in C, I saw that there are plenty of ways to open a file with fopen using words as a,r,etc.. Everything ok, but I read also that if to that word I add b that become a binary file. What does it mean? Which are the differences with a normal file?
|
Opening a file in text mode causes the C libraries to do some handling specific to text. For example, new lines are different between Windows and Unix/linux but you can simply write '\n' because C is handling that difference for you.
Opening a file in binary mode doesn't do any of this special handling, it just treat... |
I am trying to think how to write a function that get char* and return a pointer to the same char but after added to his end few constant characters.
```
char* addExtension(char* FileName)
{
}
```
|
That's just what the standard library functionstrcat()(for "string concatenate") does, I think. You should look into using it.
Also beware of the dangers of buffer overrun, a function such as this (andstrcat(), for that matter) is inherently unsafe since it doesn't include information about available space.
|
In my program, I receive input from the keyboard. I put that input in astructthat contains twocharfields and 1intfield. How can I write into the entirestructusing only a function?
Idon'twant to write into each member of thestructindividually.
|
C doesn't have "instructions".
You should be able to use a single function call, such as:
```
fwrite(&mystructure, sizeof mystructure, 1, myfile);
```
But this isn't without drawbacks:
This makes the file-format depend on your current CPU and compiler, which is often a bad idea; it will make it very hard to preser... |
```
#define Map(From, To, val) \
Map__##From__##To(val)
Map(TYPEA, TYPEB, 22);
```
In the above code I am wondering whyMap(TYPEA, TYPEB, 22);is getting expanded toMap__From__TYPEB(22);and notMap__TYPEA__TYPEB(22);
I used gcc -E for expansion.
|
BecauseFrom__is not a token inMapand hence, preprocessor does not look it up.. fix is :
```
#define Map(From, To, val) \
Map__##From##__##To(val)
```
|
Between the
```
int array[100][100];
```
And
```
int array[100][100]={0};
```
In the first one, when I print all the elements of the array then after 94th row, halfway through it, I start to get the garbage values but all the values before that are 0, whereas for the second one, all the values are 0.
Does not the... |
Does not the first declaration too initialize with a default 0 value?
No. Assuming this is a locally scoped variable, your first declaration does not result in any initialization at all.
How come not all of the values in the array are garbage and why only after 94th row the garbage values are appearing?
Uninitializ... |
can you tell me please, what is wrong with this codehttp://pastebin.com/A2upK4Lx? Cause it gives me Runtime: 0.00000, and that is weird, because I didnt spot an error there. Is it possible, that the code is fine, but the code executes so fast, that even C cant print it out (but I think that is highly unlikely)?
thank... |
Is it possible, that the code is fine, but the code executes so fast, that even C cant print it out (but I think that is highly unlikely)?
No, that's very likely indeed. We're not anymore in the 70's, computers arefast.
|
I almost understand how tail recursion works and the difference between it and a normal recursion. Ionlydon't understand why itdoesn'trequire stack to remember its return address.
```
// tail recursion
int fac_times (int n, int acc) {
if (n == 0) return acc;
else return fac_times(n - 1, acc * n);
}
int facto... |
The compiler is simply able to transform this
```
int fac_times (int n, int acc) {
if (n == 0) return acc;
else return fac_times(n - 1, acc * n);
}
```
into something like this:
```
int fac_times (int n, int acc) {
label:
if (n == 0) return acc;
acc *= n--;
goto label;
}
```
|
There's a variable:
```
char segment = 0;
```
After 1 or with bit 15, segment = 1;
Just means this bit check already.
Question is how to cancel the mark of bit 15 (set back to 0)?
Use "~"?
|
Following program sets bit, clears bit and toggles bit
```
#include<stdio.h>
void main(void)
{
unsigned int byte;
unsigned int bit_position;
unsigned int tempbyte = 0x01;
//get the values of the byte and the bit positions
//set bit
byte = (byte | (tempbyte << bit_position));// set the bit at the position given by b... |
I have a application in C programming which uses jansson library(json library written in C). I'm trying to view value of json_t object in gdb but it just prints
```
(gdb) p jmsg
$20 = (json_t *) 0x69c350
(gdb) p *jmsg
$21 = {type = JSON_OBJECT, refcount = 1}
```
How is it possible to view the value of json_t in gdb.... |
When in GDB, you can make function calls directly. Jansson library has a json_dumps(json_t *, int flags) API that returns a char* string of the json_t object.
So while in GDB, just simply do:
```
(gdb) call json_dumps(obj, 0)
```
GDB will then print the string output of your json object.
|
I am trying to accomplish the following using nested for loops (C language):
```
a[0] = b[0][0];
a[1] = b[1][0];
a[2] = b[1][1];
a[3] = b[2][0];
a[4] = b[2][1];
a[5] = b[2][2];
a[6] = b[3][0];
a[7] = b[3][1];
a[8] = b[3][2];
a[9] = b[3][3];
```
I have this:
```
for (j=0; j<3; ++j... |
Two fixes.
include a countermake your bound check inclusive
Illustrated:
```
int i=0;
for (j = 0; j <= 3; ++j)
for (k = 0; k <= j; ++k)
a[i++] = b[j][k];
```
Ideone
|
I have a problem with debugging a process on arm + Linux platform:
This is a daemon process working with CAPWAP protocol, so it continuously communicates with another remote process. When it crashes with a segmentation fault, my usual means of debugging is to add some log output viaprintf, to find where the process h... |
You could also enablecore(5)dump, then usegdbpost-mortem on that core with
```
gdb yourprogram core
```
To enable core dump, you need to call thesetrlimit(2)syscall withRLIMIT_CORE, usually in some parent process (e.g. the shell withulimit)
BTW, you could also start your program thrugdbusing
```
gdb --args yourpro... |
Its easier if I tell you why I am asking this- in case I do not ask the correct question. When inlining functions you can sometimes make the code too big and therefore cause TLB misses. I also believe you would end up with not L1 data, but L1 instruction cache misses if you use inlined code too much.
How can one dete... |
Most compilers will generate assembly language output with the right incantation (e.g., -Fa for VC++, -S for most others).
VC++ can also produce a map file, which is often easier to sort things out from -- it's produced by the linker, so it includes things like link-time optimization and tells you the addresses of sy... |
I have a simple question about structures in C.
I have this struct and this function:
```
struct Vec2
{
int x;
int y;
}
void draw(Sprite* sprite, struct Vec2 pos);
```
Is there anyway to do the equivalent in c++?
```
draw(foo, new Vec2(10, 20));
```
I tried this but the compiler doesn't agree with me:
```
d... |
If your compiler supports C99 or later, you can use acompound literal:
```
draw(foo, (struct Vec2){10, 20});
```
or, if you want to be more explicit about the member names:
```
draw(foo, (struct Vec2){.x = 10, .y = 20});
```
(Note that Microsoft's C compiler doesn't support C99, which could limit the portability o... |
I am using tornado 2.2 in Vxworks PPC board for running my C program. What is the Tornado shell command to get current sytem time. Google is not giving any answer for it, its only giving details about C system call to find system date.
This vxworks board is connected to a windows xp machine. I am able to see system t... |
Once the vxwork board is rebooted, system time will get resetted to 1970.timecommand will returns the number of seconds ticked from 1970. To get and set the time in standard presentable format, we have to implement aC program.
|
This question already has answers here:how to get the string-lengths stored in array (C)(4 answers)Closed9 years ago.
Ok I am in the process of making a simple hangman game. I need help pulling a string which is in an arraydict[num]num being a random number. I just need a way to get that string out and usestrlen()a... |
if the type of the dict array is char then to get the length
```
strlen(dict)
```
and not
```
strlen(dict[num])
```
and if the
```
strlen(dict)
```
gives segmentation error then chek that your array is filled with string I mean check the string in the array end with the null character'\0'
|
Is it possible to do a renegotiation of the SSL handshake while the current SSL connection remains active. When the new handshake has succeeded the server should respond with a confirmation of the new handshake.
I've searched on SSL renegotiation but I couldn't find anything concrete. Does anyone know if something li... |
Yes, renegotiation is part of TLS protocol. It can be both client- and server-initiated. Support for it depends on the implementation. Also, renegotiation made anattackon TLS possible.
|
I write program in C in Visual Studio 2008. I want to have array initialized from binary file. But i don't want to have binary file alongside with .exe file. So I must embed binary file into my .exe. I searched over Google. Most of answers advice me to use "Resources" in VS. But I don't know OOP and I don't need such ... |
Write a simple script in your favorite scripting language and process the binary file into a a comma-delimited set of values before the compilation (there are probably free tools available online as well). Embed this set of values into your source C file to statically initialize an array. E.g., the result can be somet... |
I am trying to use a macro in sprintf statement. It is like this :
```
#define MACR 6
....
int Number= 5;
char Formatted[30];
sprintf( Formatted, "%06d", Number );
```
Here I would like to use MACR instead of 6. Can anyone help me please?
|
Use the*format specifier to pass the width as argument. Something like this should work:
```
sprintf( Formatted, "%0*d", MACR, Number );
```
But please use a constant not a MACRO.
|
currently I search achar *withstrstrbut I dont want to search in the complete one, only from the 42. char to the end.
How can I achieve this?
|
Just providestrstr()with a pointer to the first character to include in the seach:
```
if(strstr(the_haystack + 42, "the needle") != NULL)
printf("found needle at end of haystack!\n");
```
Of course, this assumes thatthe_haystackreally is at least 42 characters long.
|
This question already has answers here:Accessing bit-field in C by its address(3 answers)Closed10 years ago.
I'm going through few C aptitude questions. This one seemed tricky, can any one explain?
```
struct {
int foo : 4;
} baz;
int *example()
{
return &baz.foo;
}
```
This is invalid code, but i couldn't... |
```
int foo : 4;
```
declaresfooas a bit-field. One must not take the address of a bit-field.
Section 6.5.3.2 starts:
The operand of the unary&operator shall be either a function designator, the result of a[]or unary*operator, or an lvalue that designates anobject that is not a bit-fieldand is not declared with the... |
Why is the following code invalid?
```
void foo()
{
char hello[6];
char *foo = "hello";
hello = foo;
}
```
But how the following code is valid?
```
void foo()
{
char hello[] = "hello";
char *foo = hello;
}
```
|
You are are trying to assign the array as a pointer. This is invalid. Arrays are like pointer constants in that they can’t be used as lvalues – they can’t be reassigned to point to somewhere else. The closest you can get is to copy the contents of foo into hello.
In second case, hello is an array of chars and foo is ... |
I have two static libraries lib1.lib, lib2.lib (not their code) with the same function-prototypes, but with different implementations.
I tried including both, and it seems to use always the implementation from the first library included.
If I include both of them in my project, is there a way to choose the implement... |
I think it should be possible to write thin wrapper DLL's that link against each of the static libraries. Notice that this will only work iflib1.libandlib2.libare static libraries and that such a wrapping will incur a performance hit.
|
I initially get an address of a pointer from another processor and I need a pointer that points to the items at that address. Don't worry too much about the MPI_Recv, just know that I am getting information from another processor. So I have:
```
MPI_Recv(&a, sizeof(int), MPI_INT, 0, 1, MPI_COMM_WORLD, &status);
c... |
Each process has its own separatevirtual address spaces. Pointers from one process are meaningless in the context of another process.
You have several options:
Usethreadsinstead of processes.Useshared memory.Send the actual data rather than just a pointer.
Only the last option is viable if your processes can reside... |
This question already has answers here:What is the difference between const int*, const int * const, and int const *?(23 answers)Closed10 years ago.
```
char const*const variablename = " ";
```
what does it mean?
is it same as pointer declaration?
Please anyone explain.
Thank you in advance!
|
It's aconstpointer to aconstC string. This means that neither the contents of the string, nor the pointer itself, can be changed.
|
I'm working on a parser for C. I'm trying to find a list of all of the context-free derivations for C. Ideally it would be in BNF or similar. I'm sure such a thing is out there, but googling around hasn't given me much.
Reading the source code for existing parsers/compilers has proven to be far more confusing than he... |
This is an ANSI-C grammar, updated to C11 standard. Should serve your purpose.
http://www.quut.com/c/ANSI-C-grammar-y.html
|
```
tempValue = input2[0] << 8;
```
I can't figure out what the<<does in this line of code. What is this used for?
|
It assignstempValuethe value ininput2[0]shifted to the left by 8 bits.
Here is a link about bit shifting in C:http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/bitshift.html
|
As I'm traversing through a linked list it seg faults. I can't figure out why it's doing so. My assignment is to RECURSIVELY (all functions) insert integers in order, make a function to check for an integer, print list, print list backwards, delete a node, and delete an entire list. I am on the last part and have bee... |
You are first freeing the memory used by head and then passing a member of head as argument to "deleteList".
I think it should be first deleteList and then free:
```
if (head)
{
deleteList(head->next);
free(head);
}
```
|
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.
Need to parse a url or ip by its de... |
Have a look atstrtokandstrlenin string.h
```
#include <stdio.h>
#include <string.h>
int main(void) {
char url[] = "www.google.com";
char *token;
token = strtok(url, ".");
while(token != NULL) {
printf("%s -%d\n", token, (int)strlen(token));
token = strtok(NULL, ".");
}
return ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.