question
stringlengths
25
894
answer
stringlengths
4
863
I'd like to write a small C program that reads from a file while it is actively being written to. Any ideas?
If you have control over the writing process you should usemmap()withMAP_SHAREDin both reader and writer. This way the reader will see the changes done by the writer practically immediately. Also, note that Linux does not make any snapshot of the data in the file when you open the file, so you should see the changes ...
OS: Ubuntu Linux 10.10 Kernel: 2.6.35-30 Query: I need to establish a robust communication between a Windows process and an embedded device on the above platform. What can be a possible solution in this case? Socket programming has already been ruled out in this case. It may sound to you as a very fundamental questio...
Could you clarify your question? Do you really mean "Windows USB device driver"?What is your full setup? (For example:The host system is running Ubuntu (Kernel 2.6...) attached to one of it's USB ports is a USB to serial adapter which is connected to the serial port of an embedded device. I need to communicate with...
I have called a method using a secondary thread. From inside the method i need to call a method from main thread. here is the structure ``` void main_thread_method() { } void secondary_thread_method() { //do something here call main_thread_method() here using main thread } pthread thread1; pthread_create (...
If your main thread is running a message pump you can post a message somehow to execute a function when your message is received. Otherwise have a simple queue ( appropriate locking of course ). Add enough data into the queue so that main_thread_method can be called. (args etc). Periodically poll the simple queue fo...
I'm trying to solve problem 14 on project euler, and my initial brute force attempt has me stumped. For some reason, the code encounters a cycle between 13 and 19. I don't think I can righteously proceed onto non-brute methods unless I can first get the brute-force method to at least compute correctly. My code looks...
n & 0x01will be1ifnisodd, not if it iseven. Changeis_evento return!(n & 0x01).
I need a CSV reader that will output a NxN (weighted) adjacency matrix (N is not known from the beginning). Of course I can use strtok() and friends to parse this, but if something is already available and complete enough, I would appreciate any pointers.
maybe you could usethisas base if you don't find anything better, it should be fairly simple to modify to handle NxN. It works by reading the whole file into a buffer, then sets pointers into the buffer by finding the delimiters and settings those to \0.
I am creating a simple Unix shell in C. I use the fork() to clone the process and exec to execute a new one. It works fine when you are inputting data for the first time in the shell. But when it comes the second iteration fork returns -1. e.g ...>ls -l / /results here/ ...>ls -l / forking failed here is a part ...
Change your firstifbranch to this: ``` if((pid=fork())<0){ perror("forking failed"); exit(0); } ``` This will tell you what went wrong.
I have a program written in C that runs on Linux, MacOS and Windows. Is there a way I can call a function and generate a stack trace? This would be super-useful for me. Ideally I'd like to do it on all three platforms, but Linux is the most important. (Windows is being compiled via mingw.) Thanks.
For example, in GCC and the GNUlibcC library, you can usebacktrace(). As @slugonamission suggests, Windows offersCaptureStackBackTrace()- thanks! Other platforms may offer similar features. (This is obviously a platform-dependent question.) (On a related note, there also existself-disassembly libraries.)
I want to add elements to the my linked list order by ascending but my code just hold minimum node of the lists correctly. My function take an argument as data. Anybody have any idea about my fault? ``` while(Node->nextPtr!=NULL && capture!=1) { if(Node->nextPtr->data > data){ capture = 1; Node->n...
why not something in the lines of: ``` while(Node->data < data && Node->nextPtr!=NULL) Node = node->nextPtr; Temp->nextPtr = Node->nextPtr; Node->nextPtr = Temp; ``` Seems clearer, and you don't need to keep track of captured and nextPtr. (I apologize for any small mistake, it's kinda late here :P) Cheers
I read it's possible to use C/C++ code in PHP by writing an extension. Is there a simpler way, like wrapping magic or things like that (I must say, I heard the word, but don't know much about what a wrapper is).
Compiling a php extension isn't very hard. There is a little API to learn just like C programs has the main function and how to pass variables to the main function.
I am writing this on an Arduino so I don't believe the full scope of C or C++ is available to me, or is it? I have a sequence of numbers being generated and I want to collect the value of the tens and units columns off of the end; For example, if the first generated number were 8028, I would want to minus 28 from it...
You would want to use amodulusif you can, in c/c++ its the%operator: ``` 8028 % 100 3479 % 100 ``` etc
I'm new to C and am trying to use the read function. I want to take what's in the buffer (tempChar) and put it in another char array (str). This is so I can run the read function again and add on to str later (because tempChar will be rewritten by the 2nd read function). Like this: ``` char tempChar; read(0, &temp...
you need to have enough storage to store the 10 characters you are reading you declared ``` char tempChar ``` which can hold 1 character. Instead declare tempChar as ``` char tempChar[10]; ```
I'm usingcmake 2.8.3to generate a C/C++ project file forxcode 3.2.5; the build goes generally fine, but I have to manually set the "Product Name" each time I generate the xcode project (inProject / Edit Project Settings / Packaging). If I fail to set this product name,xcoderefuses to build the project, and exits repo...
Have do you tried something like this? ``` set_target_properties(your_target PROPERTIES XCODE_ATTRIBUTE_PRODUCT_NAME "aaa") ``` I've replaced Mac OS X with Linux on my MacBook, so I can't check this suggestion.
Imagine a function myFunctionA with the parameter double and int: ``` myFunctionA (double, int); ``` This function should return a function pointer: ``` char (*myPointer)(); ``` How do I declare this function in C?
typedefis your friend: ``` typedef char (*func_ptr_type)(); func_ptr_type myFunction( double, int ); ```
I have a question for you, is it possible to the the following in C? I mean: In the code I would have something like ``` char example[] = "Single" ``` then do edit this string, I would copy to input ofscanf, and then I could just use backspace to delete the last char 'e', then I would press enter, andscanfwould st...
From what I understand you want to interactively edit string on your terminal. Functions fromstdio.hdon't offer such functionality. They only read and write data. You can use libraries such asreadlineorncursesto achieve this.
I am writing and implementation of the Miller-Rabin primality test. I believe I have implemented it correctly, but I cannot get my C code to compile on solaris. The code compiles fine in OS X and Debian, but I am getting linking errors in solaris. When I try to link my program, I get the following errors: ``` gcc -Wa...
You need to link with the-lm. Try: ``` gcc -Wall prime.o -o prime -lm ``` There's also aC FAQabout this.
according to me following while loop should be infinite but it runs only thrice ``` main() { int i=3; while(i--) { int i=100; i--; printf("%d..",i); } } ``` it outputs99..99..99 but according to me it should run infinite times as every time control enters while loop it g...
The variableithat checks the condition is the one you declared inmain()not the one inside the loop. Both are different variables you are confusing them as one, the compiler doesn't get confused as easily as you were. Inside the loopirefers to the one you declared inside the{}but outside the{}theirefers to the one de...
This code run on Turbo C but not on gcc compilerError:syntax error before '*' token ``` #include<stdio.h> int main() { char huge *near *far *ptr1; char near *far *huge *ptr2; char far *huge *near *ptr3; printf("%d, %d, %d\n", sizeof(ptr1), sizeof(ptr2), sizeof(ptr3)); return 0; } ``` Turbo C output is :4, 4 , 2Can y...
The qualifiershuge,farandnear, arenon-standard. So, while they might work in Turbo C, you can't rely on them working in other compilers (such as gcc).
I have aconvex polygonexpressed by points. Points are expressed byarray of x-coordinatesandarray of y-coordinates. For example: ``` X = {6, 1, 5, 0, 3} Y = {4, 0, 0, 4, 6} ``` How can Isortthis points byclockwise? Number of points is not always the same, but polygon is still convex. Is there a solutionwithout us...
I'd recommend you to sort them by polar angle, but it's better to have a point inside of convex polygon as an origin to do that. to get such a point, you can just use a middle point of any diagonal of your poligon, for example ( (x[0] + x[2])/2, (y[0]+y[2])/2 ).
There is a piece of C code ``` int i, j = 0; for (i = 0, j = n-1; i < n; j = i++) { // array operations } ``` that I'm trying to convert into Lua code ``` local j = n-1 for i = 1, n do -- arrays are 1-based in Lua -- array operations j = i+1 end ``` but for some reason Lua code doesn't work. Am I getti...
Imagine an array as a circular buffer.iis the current item andjis always the previous one: ``` n = 5 local j = n for i = 1, n do -- arrays are 1-based in Lua -- array operations io.write('i=', i, ' j=', j, '\n') j = i end ``` Demo: ``` i=1 j=5 i=2 j=1 i=3 j=2 i=4 j=3 i=5 j=4 ```
I'm learning to use the write function and am trying to print only a part of a buffer array of chars. So it looks like this: ``` char *tempChar; char *buf; buf=&tempChar; read(0, buf, 10); write(1, [???], 1); ``` I thought about putting buf[3] where the [???] is, but that didn't work. I also thought about using te...
You would usebuf + 3. This is pointer arithmetic. It takes buf and gives you a new pointer 3 characters down.buf[3]is equivalent to*(buf + 3). Note the unwanted dereference. As another note: ``` buf=&tempChar; ``` is probably not right. That assigns the address of the tempChar variable to buf, which is probably...
I'm using the read function to take in one character, then running the read function again. Before I run the function again, I want to save what's in the buffer to a char variable. Like this: ``` void *buf; read(0,buf,1); char tempChar; ``` I want to store what's in *buf into the char tempChar. I know I can't jus...
You can do it like this: ``` char tempChar; read(0,&tempChar,1); ``` So there's actually no need to have a separate buffer at all.
I want to define an array outside main function so that it is shared by all threads not only main thread. When the user runs the program, his argument should be the size of the array. How can I achieve this in C?
You can't with a true array. You can do it with a pointer: ``` int *p; int main(int argc, char *argv[]) { size_t x; if (argc < 2) return; size_t x = strtoul(argv[1], NULL, 10); p = malloc(x * sizeof *p); return 0; } ```
Can any of you guys tell me what "int filedes" refers to?http://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html I've noticed I can put any int in there and it seems to work but I don't know what it's for... Thanks.
It's a file descriptor. Seehttp://en.wikipedia.org/wiki/File_descriptor. Since it represents an offset to a table lookup of files and pipes, there may be multiple descriptors that could return valid data. 0=stdin and 2=stderr will exist by default, or you can look at the open function to create your own.
Is there a predefined C macro for detecting the version of OS X? I know__APPLE__and__MACH__exist, but those are binary. Is there a specific value for__APPLE_CC__that indicates Lion? In particular, Lion added a definition ofgetline()to<stdio.h>in Lion and it would be nice to be able to detect whether or not code was c...
TheAvailability.hmacros allow you to check for compile- and run-time version dependencies. See the discussionhere.
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...
My suggestion would be that you check out the GNU C Library source code for this. You can download it here:http://www.gnu.org/s/libc/
Is there a way to convert cvMat to cvMAt* in opencv? I basically have to convert a Mat object to cvMat*. So initially I convert the Mat object to a cvMat object. Now, I need to convert it into a cvMat* pointer.
This isn't an OpenCV question, it's basic C. If you're this unfamiliar with C, perhaps you should try some other solution. That said, converting fromObject somethingtoObject *somethingis as easy as passing&somethingto the function you're calling.
If I have a character like the following: ``` wchar_t c = '\x0A' ``` What's an easy way to convert it so that it becomes something like: ``` wchar_t dst[] ==> "0A" ``` Basically, the hex value of c becomes a string value.
The integral value ofcwould be0x0A(10in base 10). You can usesprintfto format it as hex: ``` wchar_t c = '\x0A'; int c_val = c; char string[3]; sprintf( string, "%.2X", c_val ); ``` Note the intermediatec_valvariable is not needed, only added for clarity or you can do it manually: ``` int c_low = c & 0x0F; int c_...
I am trying to set a variable name and variable value in the environment of Windows by using this function ``` void env_add(char varname[], char varvalue[]) { } ``` The problem is that i do not know how to put both of these variables toint putenv(char *string); Should I combine them into one char array or not? Th...
Yes, you should combine them into a single string. The string has the form"name=value". ``` char* buffer = (char*) malloc( strlen(name) + 1 + strlen(value) + 1 ); strcpy( buffer, name ); strcat( buffer, "=" ); strcat( buffer, value ); putenv( buffer ); free( buffer ); ```
Is there any command line interactive shell for C just like in Python ? Actually, I'd like to make one if its not done, at least if a stable one is still not present. I'm good at C and basics of python.. What all things I should be knowing to really do this kind of project ?
Yes, you can usec-repl. There is some SO discussion on the package inthis question. The project might be old; there have been no checkins to itsgithub master branchsince October, 2009. UPDATE - I found this SO question which has better answers:Is it possible to build a interactive C shell?
I am using_stati64()in my file manager so that I can get the size of files over 4gb. My code looks normal: ``` struct _stati64 buf; _stati64(ep->d_name, &buf); ``` The thing is, sometimes_stati64works properly, sometimes I get huge values. I even checked with gdb, by doingprint bufand still get bad values, so the p...
You need to check the return value of_stati64. If it's not 0, you won't have valid results. If your actual code does check the return value, the error is most likely that you are somehow corrupting the structure after_stati64returns. The last possibility is that the "bad values" you get are actually valid and good v...
I have a char byte that I want to convert to an int. Basically I am getting the value (which is 0x13) from a file using the fopen command and storing it into a char buffer called buff. I am doing the following: ``` //assume buff[17] = 0x13 v->infoFrameSize = (int)buff[17] * ( 128^0 ); ``` infoFrameSize is a type i...
^is bitwise xor operation, not exponentiation.
In C how much space does a bool (boolean) take up? Is it 1 bit, 1 byte or something else? Does it matter if the program is 32-bit or 64-bit?
All references to the standard herein refer toISO C17. The following code will show you the size of a boolean, which must be at least one given that this is the minimum addressable unit: ``` printf("%zu\n", sizeof(_Bool)); // Typically, but not necessarily, 1. ``` The standard (6.2.5 Types, though this is also the ...
I have a number of data structures (trees, queues, lists), created using dynamic allocation routines (malloc, calloc). Under some critical conditions, the program should terminate. Traversing all objects to free their memory takes long time. Is it safe to avoid traversing all data structures just before program stops...
All the memory dynamically allocated by a process is released back to the OS on process termination, doesn't matter intentionally or via a crash. Same happens with files and sockets - ref counts inside the kernel get decremented and resources get released if there are no more references. An exception to the above mig...
I have a pretty simple question. Is there a way to dynamically shift bitwise to the left OR to the right, e.g. depending on the sign of an int. ``` signed int n = 3; signed int m = -2; int number1 = 8; int number2 = 8; //number1 shift n; //number2 shift m; ``` In this case I want to shift number1 3 bits to the lef...
For 32 bit: x = (((long long)x) << 32) >> (32 - n)
Is there any command line interactive shell for C just like in Python ? Actually, I'd like to make one if its not done, at least if a stable one is still not present. I'm good at C and basics of python.. What all things I should be knowing to really do this kind of project ?
Yes, you can usec-repl. There is some SO discussion on the package inthis question. The project might be old; there have been no checkins to itsgithub master branchsince October, 2009. UPDATE - I found this SO question which has better answers:Is it possible to build a interactive C shell?
I am using_stati64()in my file manager so that I can get the size of files over 4gb. My code looks normal: ``` struct _stati64 buf; _stati64(ep->d_name, &buf); ``` The thing is, sometimes_stati64works properly, sometimes I get huge values. I even checked with gdb, by doingprint bufand still get bad values, so the p...
You need to check the return value of_stati64. If it's not 0, you won't have valid results. If your actual code does check the return value, the error is most likely that you are somehow corrupting the structure after_stati64returns. The last possibility is that the "bad values" you get are actually valid and good v...
I have a char byte that I want to convert to an int. Basically I am getting the value (which is 0x13) from a file using the fopen command and storing it into a char buffer called buff. I am doing the following: ``` //assume buff[17] = 0x13 v->infoFrameSize = (int)buff[17] * ( 128^0 ); ``` infoFrameSize is a type i...
^is bitwise xor operation, not exponentiation.
In C how much space does a bool (boolean) take up? Is it 1 bit, 1 byte or something else? Does it matter if the program is 32-bit or 64-bit?
All references to the standard herein refer toISO C17. The following code will show you the size of a boolean, which must be at least one given that this is the minimum addressable unit: ``` printf("%zu\n", sizeof(_Bool)); // Typically, but not necessarily, 1. ``` The standard (6.2.5 Types, though this is also the ...
I have a number of data structures (trees, queues, lists), created using dynamic allocation routines (malloc, calloc). Under some critical conditions, the program should terminate. Traversing all objects to free their memory takes long time. Is it safe to avoid traversing all data structures just before program stops...
All the memory dynamically allocated by a process is released back to the OS on process termination, doesn't matter intentionally or via a crash. Same happens with files and sockets - ref counts inside the kernel get decremented and resources get released if there are no more references. An exception to the above mig...
In C how much space does a bool (boolean) take up? Is it 1 bit, 1 byte or something else? Does it matter if the program is 32-bit or 64-bit?
All references to the standard herein refer toISO C17. The following code will show you the size of a boolean, which must be at least one given that this is the minimum addressable unit: ``` printf("%zu\n", sizeof(_Bool)); // Typically, but not necessarily, 1. ``` The standard (6.2.5 Types, though this is also the ...
I have a number of data structures (trees, queues, lists), created using dynamic allocation routines (malloc, calloc). Under some critical conditions, the program should terminate. Traversing all objects to free their memory takes long time. Is it safe to avoid traversing all data structures just before program stops...
All the memory dynamically allocated by a process is released back to the OS on process termination, doesn't matter intentionally or via a crash. Same happens with files and sockets - ref counts inside the kernel get decremented and resources get released if there are no more references. An exception to the above mig...
I have a pretty simple question. Is there a way to dynamically shift bitwise to the left OR to the right, e.g. depending on the sign of an int. ``` signed int n = 3; signed int m = -2; int number1 = 8; int number2 = 8; //number1 shift n; //number2 shift m; ``` In this case I want to shift number1 3 bits to the lef...
For 32 bit: x = (((long long)x) << 32) >> (32 - n)
What is the difference between constant and restrict pointers, for example: ``` int * const ptr, int * restrict ptr ```
They do completely different things. Aconstpointer will not change. Arestrictpointer will be the only way in which the object pointed to is accessed.
I came across a problem yesterday where my program failed as 32 bit process. I had a dylib compiled as 64 bit and I was using it on 64 bit application. But when I turned it to 32 bit for testing and tried to load it, it did not worked. dlopen() returned NULL? Do I need to have 32 bit and 64 bit dylib for 32 bit and ...
Yes, you need 32bit libs for 32bit processes, and 64bit libs for 64bit processes. There is no workaround.
I found (inhttp://c-faq.com/ansi/avail.html) that "An electronic (PDF) copy is available on-line, for US$18, from www.ansi.org". But at the same time, I can download it for free fromhttp://www.open-std.org/JTC1/sc22/wg14/www/docs/n1256.pdf Both are C standards, right ? What is the difference between two ?
The latter is a draft. Accurate and containing everything you need, but in draft form. This is a WG14 working paper, but it reflects the consolidated standard at the time of issue
What's the difference between declaring multidimensional arrays like this: int a[5][5]; or this int* a[5]; ? Which one is better to use? Thanks.
Bothmaybe used to declare 2-dimensional arrays. In the first case, 25 int elements are allocated in a contiguous region in memory. In this case the expressiona[i][j]is translated by the compiler to*(a + i*5 + j). The second one allocates 5 pointers toint. You can make it work as a two dimensional array by allocatin...
I would like to calculate an inverse mask for an unsigned char.meaning if the original mask 0xc0 the the inverse mask should be 0x3f.that is to say all the bits should be flipped or inverted.I have tried the below but doesn't seem to be working. ``` int flipBit(int x, unsigned char position) { int mask = 1 << posit...
Use the ~ (bitwise-not) operator. ``` inverse_mask = ~mask; ```
I don't know if anyone could kindly explain this code for me? ``` unsigned int x = 0; (x ^= x ) || x++ || ++x || x++; printf("%d\n", x); ``` when I compile this on my computer using gcc 4.2, the output is 2. Originally i thought maybe this behavior is unspecified but then i figure || will have lower precedence ove...
(x ^= x)is evaluated and it yields 0, therefore:(x++)is evaluated and ityields 0, therefore:(++x)is evaluated and it yields 2, thereforeit stops It all boils down to one rule:||only evaluates its right side if its left side is false.
``` const int num = 16; struct inputs{ double X1[num]; double X2[num]; }; ``` Gives me an error: error: variably modified ‘X1’ at file scope The same was true for 'X2'. But I remember the above is fine for C++, the above is fine (I may be mistaken for C++). Can anybody clarify this for me?
I can point you to aC FAQ: I don't understand why I can't use const values in initializers and array dimensions. What it basically says is thatnumisn't a true constant, it's just read-only. To get a true constant you would need a#define num 16. Also on that page:C is unlike C++ in this regard.
I guess the output should be "0000" but it's ffff as Not of ~ffff->0000 0000 0000 0000 ``` #include<stdio.h> int main() { unsigned int a=0xffff; ~a; printf("%x\n", a); return 0; } ```
You need to assign the value back toa: ``` a = ~a; ``` Even then, the outputted value can look like this, due to the size of the datatype: ``` ffff0000 ``` To make it work as expected (all 0s), set the initial value ofatoUINT_MAX(fromlimits.h). Doing so sets all the bits to1.
As far as I understand, the kernel has kernelthreads for each core in a computer and threads from the userspace are scheduled onto these kernel threads (The OS decides which thread from an application gets connected to which kernelthread). Lets say I want to create an application that uses X number of cores on a compu...
You should basically trust the kernel you are using (in particular, because there could be another heavy process running; the kernel scheduler will choose tasks to be run during a quantum of time). Perhaps you are interested in CPU affinity, with non-portable functions likepthread_attr_setaffinity_np
For the C statement given below i would like to know where the memmory allocation will take place. ``` char* ptr="Hello";//ptr is a automatic variable ``` then the pointer variable ptr will be allocated on the stack,but where will this string "Hello" be allocated. Is it on Stack or on Heap? And what about memory all...
The standard doesn't say (it doesn't know about "stack", "heap" etc). But in practice the answer is: Neither. The string literal will be stored in the data section, usually in a read-only page. As a side note, as Als mentions in the comments, it's undefined behavior to attempt to modify a string literal.
A function returnsTRUEon failure andFALSEon success. I see some such functions do this towards end of itself: ``` return return_code != 0; ``` or ``` return (return_code != 0); ``` And in this function, at each error case, it returnsTRUE- which is fine and what it should do in case of error. But what does above ...
I would say is trying to collapse from all the possible integer values to just those of0and1. I'm assuming that the function returns an integral type; evaluating the result as a boolean expression forces the result to just those two values.
In one file I have this: ``` #include <stdio.h> #include <stdlib.h> static struct node* mynode; struct node* example(void) { mynode = malloc(sizeof(struct node)); ...fill up the struct here... return mynode; } ``` The calling routine is: ``` #include <stdio.h> #include <stdlib.h> int main(void) { ...
Could it be you didn't declare a prototype forstruct node* example(void)and the compiler thinks it returns anint?
I have a 80k+ file that I want to generate a random word from. I want to load this file into an array to generate a random word from. How can I do this. I've already opened the file, and generated a random number to correspond with the array. Thanks
I guess the file is a dictionary. So, you have to read the file word by word - i.e. line by line if there is a word per line - copy each word in a string array (a char matrix) you preallocated and then you can use each random number as an index to access the string array and pick the "random" word. ``` size_t bytes =...
supposing to have two arrays a[N],b[N] containing only 0 and 1 values, is there a way to calculate c = a || b without a loop like the following (in C)? ``` #define N 10 char a[N]; char b[N]; char c[N]; // suppose to do some operations on a and b so that // for each i a[i] == 0 or a[i] == 1 // and the same for b /...
Since bitwise or is an operation that has to be applied to a single value, I don't think there is. Is there a particular reason you want to avoid the loop? If it's a hassle, making a function out of it is easy. Edit:The question has now changed to logical OR, but I don't think the answer is much different.
I have a C library that isnotthreadsafe -- and probably will never be. I'm calling it from C# with PInvoke and that's working out quite nicely. Now that C library has to be called from a C# program that certainly is multi-threaded. I can manage this in the C# by having each instance of the C code called from separa...
No, AppDomains will not help. If you call into your C lib concurrently, it doesn't matter which AppDomain the calls come from. If the C lib is not thread-safe, you will have to serialize access to it. Actually, having multiple AppDomains makes this harder - you will have to synchronize across the domains.
The last time I heavily used C was years ago, and it was strictly done on the Windows platform. Now, I am taking a class where it is required to develop programs to be ANSI C compliant and the code will be compiled usinggcc we a are required to compile the code using:gcc -g -ansi -pedantic -Wall how can I reproduce...
If you only dislike Ubuntu, there are other options for using GCC. For example, you can look into MinGW, which is a full set up of gcc and all related tools for windows. There are also a few IDEs, like Eclipse and Code::Blocks which I'm pretty sure ship with a C compiler that you can configure however you need. There ...
So I have this macro and a bunch others defined in my header file ``` #define COL1WIDTH 16 ``` Which I want to use to print something like this: ``` word 25 Dir1/FileB 129 Sat Jan 1 00:00:02 2011 12 1(x4), 2(x2), 3(x2), 4(x2), 5(x2) ``` How does the syntax to get the macro work? Tried a bunch and it keeps screwin...
printf("%" #COL1WIDTH "s\t", ... Read up ontoken pasting and stringizingin the C pre-processor.
here i am confused aboutfopen("filename.txt","rb")andfopen("filename.txt","r") So which use when i want to get idea about in this in detail
If you read the man page forfopen()you'll find: The mode string can also include the letter 'b' either as a last character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with C89 and has no effect; the 'b' is ignored on all POSIX...
How do I test if a__m128ivariable has any nonzero value on SSE-2-and-earlier processors?
In SSE2 you can do: ``` __m128i zero = _mm_setzero_si128(); if(_mm_movemask_epi8(_mm_cmpeq_epi32(x,zero)) == 0xFFFF) { //the code... } ``` this will test four int's vs zero then return a mask for each byte, so your bit-offsets of each correspondingintwould be at 0, 4, 8 & 12, but the above test will catch if any...
I'm trying to concatenate two uint32_t and get back a uint64_t. Here's my method ``` uint64_t concat_int1_int2 (uint32_t int1, uint32_t int2) { uint64_t concatenated = int1; return concatenated << 32 | int2; } ``` This seems to be extremely slow (I need to do it ~1,000,000 times and it is taking ~ 6 minutes). Tw...
The way you are doing it is correct. It may help toinlinethe function. Most likely your performance problem is in code you haven't shown us.
Is it possible to retrieve a file's name in C? If a file is created like the following: ``` FILE *f = fopen ("foo.txt", "r"); ``` And the "foo.txt" comes from a variable out of scope. Is there a way to retrieve it from the FILE struct?
Youcan'tin fact retrieve the file names from yourFILEobjects. However, if the name being passed tofopenis important to you, and that variable is out of scope for whatever reason, you could always wrap aFILE*in a struct, ie. ``` struct file_with_name { FILE *f; char *name; /* OR char name[MAX] */ } ``` At leas...
rename (), link() don't work Thanks!
Have you tried using standard old C functions? ``` `fopen` the source on one partition `fopen` the destination on the other partition LOOP while `fread` > 0 `fread` from the source to a buff `fwrite` to the dest from a buff ``` And then close your files (ie.fclose). This is alsomoreportable. EDIT:If you wan...
I have a NSMutableArray and I need to sort its elements into separate C char. How to accomplish that? Or is it better to put the elements into NSStrings? I've tried this, and it crashes when I try to log the result: ``` NSMutableArray *array = [[NSMutableArray alloc] init]; ... do something to fill the array ... ...
Dont see any specific reason to convertNSStringto C chars. To sort an array full ofNSStringstry this method - ``` NSMutableArray *array = [[NSMutableArray alloc] init]; sortedArray = [array sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; NSString *string = [sortedArray objectAtIndex:0]; NSLog(@...
Having done some C++ I have noticed that C also has structs - surely C should be considered OOP if it has them?
Because it does not have some of the basic OOPs features of:InheritancePolymorphism and so on
Say, I want to call a function with the following signature in inline assembly of gcc. How can I do that? ``` int some_function( void * arg ); ```
Generally you'll want to do something like ``` void *x; asm(".. code that writes to register %0" : "=r"(x) : ... int r = some_function(x); asm(".. code that uses the result..." : ... : "r"(r), ... ``` That is, you don't want to do the function call in the inline asm at all. That way you don't have to worry about de...
What is more efficient? 8 arraysint8 myArrayx[100], or a multidimensionalint8 myArray[8][100]? I'm working with CCS compiler for Microchip PIC microcontrollers, and I need to write as fast as possible in a buffer, that is the reason of my question.
i would have to think that the multi-dimensional array would be faster. you have a much, much better chance (possibly guaranteed?) of having those arrays being placed into memory in contiguous space whereas you can not be sure that the 8 individual arrays will be "close" together in memory - hurting your locality of r...
This question already has answers here:How can I tell gcc not to inline a function?(9 answers)Closed8 years ago. Is it possible to prevent the gcc compiler from inlining a particular function. If so, how? Don't tell me to reduce the optimization level. I want all optimizations on, but mark a particular function to n...
You should use thenoinlineattribute like this : ``` void the_method_you_dont_want_to_inline() __attribute__ ((noinline)) { ... } ``` or in recent versions of GCC : ``` __attribute__((noinline)) void the_method_you_dont_want_to_inline() { ... } ```
I have a NSMutableArray and I need to sort its elements into separate C char. How to accomplish that? Or is it better to put the elements into NSStrings? I've tried this, and it crashes when I try to log the result: ``` NSMutableArray *array = [[NSMutableArray alloc] init]; ... do something to fill the array ... ...
Dont see any specific reason to convertNSStringto C chars. To sort an array full ofNSStringstry this method - ``` NSMutableArray *array = [[NSMutableArray alloc] init]; sortedArray = [array sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; NSString *string = [sortedArray objectAtIndex:0]; NSLog(@...
Having done some C++ I have noticed that C also has structs - surely C should be considered OOP if it has them?
Because it does not have some of the basic OOPs features of:InheritancePolymorphism and so on
Say, I want to call a function with the following signature in inline assembly of gcc. How can I do that? ``` int some_function( void * arg ); ```
Generally you'll want to do something like ``` void *x; asm(".. code that writes to register %0" : "=r"(x) : ... int r = some_function(x); asm(".. code that uses the result..." : ... : "r"(r), ... ``` That is, you don't want to do the function call in the inline asm at all. That way you don't have to worry about de...
What is more efficient? 8 arraysint8 myArrayx[100], or a multidimensionalint8 myArray[8][100]? I'm working with CCS compiler for Microchip PIC microcontrollers, and I need to write as fast as possible in a buffer, that is the reason of my question.
i would have to think that the multi-dimensional array would be faster. you have a much, much better chance (possibly guaranteed?) of having those arrays being placed into memory in contiguous space whereas you can not be sure that the 8 individual arrays will be "close" together in memory - hurting your locality of r...
This question already has answers here:How can I tell gcc not to inline a function?(9 answers)Closed8 years ago. Is it possible to prevent the gcc compiler from inlining a particular function. If so, how? Don't tell me to reduce the optimization level. I want all optimizations on, but mark a particular function to n...
You should use thenoinlineattribute like this : ``` void the_method_you_dont_want_to_inline() __attribute__ ((noinline)) { ... } ``` or in recent versions of GCC : ``` __attribute__((noinline)) void the_method_you_dont_want_to_inline() { ... } ```
I wanted to know more about tools that assist in writing code-generators for C. Essentially how do we achieve functionality similar to c++ templates.
Even though it's not a perfect solution and it takes some time to master it, I've used them4 macro processorin the past for generic C code generation (kinda like C++ templates). You may want to check that out.
I am working on a project in embedded c.The project is the electronic Cash Register.In this project i need to send the sale data throughgprson to a server our own made application in C#. Now i have to change the ip of the server on the machine side because of dynamic ip.i want to implementdnsin my Machine so that i...
Is your IP dynamic because of your ISP setup? If so i'd say the easiest way would be to sign up to someone likeno-ip.com. their free service will give you a url and an application to install on your server. When your ip changes on the server the application updates their records so the url is routed to the correct IP...
I was going through a possible implementation method for library functionstrcpy. It is : ``` void strcpy(char *src, char *dest) { while (*dest++ = *src++) ; } ``` How can this possibly work without check of'\0'??
The result of*dest++ = *src++is the value of*srcbefore the increment ofsrc. If this value is\0, the loop terminates.
I have a bunch of file references when i run doxygen on my c code and I'd rather it not say where on my machine the file is located. how do i get rid of this in the config file? Thanks
In Doxyfile, set ``` FULL_PATH_NAMES = NO ```
Am running this C program, but instead of answering "The answer is 10", it sends back the message: "The answer is 0", even though it breaks at the right time. Can you tell me what's wrong? ``` #import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { int i; for(int i = 0; i < 12; i++){ ...
The problem is you have twoi's. ``` int main (int argc, const char * argv[]) { int i; //Declares outer i for(int i = 0; i < 12; i++) //Declares a NEW i { printf("Checking i = %d\n", i); if(i + 90 == i * i) { break; } } printf("The answer is %d.\n", i); ...
I am seeing a lot of pages with std:: stuff:: more stuff when I run my doxygen on my c code. How do I get rid of this in the config file? Thanks in advance :)
Those arenamespaceswhich is a feature of C++.Your code must be having some C++ source files perhaps. They indicate which namespace/scope a class resides in.Ideally, You should not get rid of those. They are a part of documentation. # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen# will show memb...
I am writing a realloc function and currently my realloc handles two cases (not counting the null cases) If enough memory exists next to the block, expand itelse allocate a new block and do a memcpy My question is, are there any more cases I should be handling? I can't think of any. I thought of a case where the pr...
Include the case where the new size is smaller than the old size; ideally you should split your current block and make the end of it free.
I'mverynew to Fortran. Currently I'm writing (or trying to write) a fortran application which calls a C-library. I've got a few things working so far but I'm stuck with the init-function from the library which expects argc and argv just to get the program name which is calling the function. The C-library expects poi...
You will probably need to write your own wrapper function in C, init_fortran, or similar which you call from Fortran and takes arguments in a way you can express in Fortran, then converts them to what the C init function expects.
I tried this function to convert a string to _int64 but it didn't work : ``` _int64 lKey = _atoi64("a1234"); ``` lKey value is always zero and doesn't work except the string is only digits like "1234" I read solutions using C++ string stream but I want to write my application in pure C
The function does indeed work. As thedocumentation states: Each function returns the __int64 value produced by interpreting the input characters as a number. The return value is 0 for _atoi64 if the input cannot be converted to a value of that type. So you have to make sure that a correct string is passed. Otherwise...
I was going through a possible implementation method for library functionstrcpy. It is : ``` void strcpy(char *src, char *dest) { while (*dest++ = *src++) ; } ``` How can this possibly work without check of'\0'??
The result of*dest++ = *src++is the value of*srcbefore the increment ofsrc. If this value is\0, the loop terminates.
I have a bunch of file references when i run doxygen on my c code and I'd rather it not say where on my machine the file is located. how do i get rid of this in the config file? Thanks
In Doxyfile, set ``` FULL_PATH_NAMES = NO ```
Am running this C program, but instead of answering "The answer is 10", it sends back the message: "The answer is 0", even though it breaks at the right time. Can you tell me what's wrong? ``` #import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { int i; for(int i = 0; i < 12; i++){ ...
The problem is you have twoi's. ``` int main (int argc, const char * argv[]) { int i; //Declares outer i for(int i = 0; i < 12; i++) //Declares a NEW i { printf("Checking i = %d\n", i); if(i + 90 == i * i) { break; } } printf("The answer is %d.\n", i); ...
I am seeing a lot of pages with std:: stuff:: more stuff when I run my doxygen on my c code. How do I get rid of this in the config file? Thanks in advance :)
Those arenamespaceswhich is a feature of C++.Your code must be having some C++ source files perhaps. They indicate which namespace/scope a class resides in.Ideally, You should not get rid of those. They are a part of documentation. # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen# will show memb...
I am writing a realloc function and currently my realloc handles two cases (not counting the null cases) If enough memory exists next to the block, expand itelse allocate a new block and do a memcpy My question is, are there any more cases I should be handling? I can't think of any. I thought of a case where the pr...
Include the case where the new size is smaller than the old size; ideally you should split your current block and make the end of it free.
I'mverynew to Fortran. Currently I'm writing (or trying to write) a fortran application which calls a C-library. I've got a few things working so far but I'm stuck with the init-function from the library which expects argc and argv just to get the program name which is calling the function. The C-library expects poi...
You will probably need to write your own wrapper function in C, init_fortran, or similar which you call from Fortran and takes arguments in a way you can express in Fortran, then converts them to what the C init function expects.
I tried this function to convert a string to _int64 but it didn't work : ``` _int64 lKey = _atoi64("a1234"); ``` lKey value is always zero and doesn't work except the string is only digits like "1234" I read solutions using C++ string stream but I want to write my application in pure C
The function does indeed work. As thedocumentation states: Each function returns the __int64 value produced by interpreting the input characters as a number. The return value is 0 for _atoi64 if the input cannot be converted to a value of that type. So you have to make sure that a correct string is passed. Otherwise...
Which character should be used forptrdiff_tinprintf? Does C standard clearly explains how to printptrdiff_tinprintf? I haven't found any one. ``` int a = 1; int b = 2; int* pa = &a; int* pb = &b; ptrdiff_t diff = b - a; printf("diff = %?", diff); // % what? ```
It's%td. Seehere.
gcc (GCC) 4.6.1 I am creating some sdp using RTF 4566 and I want to get the NTP time stamp so that I can use it for the session ID. It is recommended to use the Network Time Protocol (NTP) format timestamp be used to ensure uniqueness. However, is there any function that will return the ntp time? Many thanks for an...
If anyone is interested, this is how I solved my problem. ``` /* Get the time in micro seconds to create an unique session id */ time_usec = apr_time_usec(apr_time_now()); apr_snprintf(session_id, MAX_STRING_LEN, "%lu", (unsigned long)time_usec); ``` Hope this helps someone,
Is there a '#' operator in C ? If yes then in the code ``` enum {ALPS, ANDES, HIMALYAS}; ``` what would the following return ? ``` #ALPS ```
The C language does not have an#operator, but the pre-processor (the program that handles#includeand#define) does. The pre-processor simple makes#ALPSinto the string"ALPS". However, this "stringify" operator can only be used in the#definepre-processor directive. For example: ``` #define MAKE_STRING_OF_IDENTIFIER(x) ...
I copied an example starting with main (t) { So, when compiling with gcc -pedantic I expected at least compalints about- missing return type of main (that one came)- missing type for 't' - nothing, neither with -Wall nor -pedantic. Is this just a bit generous of gcc or is there a default type in the standard? Could...
The standard makes no provision for amainfunction with 1 parameter - it requires two forms, one with 0 and one with 2. Implementations are permitted to allow others. So, GCC is doing something implementation-dependent to allow this, even if you had specified the type. C89 allows parameters with no declared type, def...
my code is : ``` #include <stdio.h> void main( int argc, char** argv) { printf("%s", argv[0]); system("pwd"); } ``` The output is: ``` [river@localhost studio]$ ./a.out /home/river/Desktop/studio ./a.out[river@localhost studio]$ ``` It seems that system("pwd") print first , then print argv[0] . why? If I ...
Theprintfcall only puts the output in a buffer. For the buffer to actually be written it needs to beflushed. Output is automatically flushed when you print a newline, so if you replace the format-string inprintfwith this:"%s\n"it should work without the call tofflush.
I have a int that has values like 1235 and 12890. I want only the 1st 2 digits from this int. How can I extract it? I thought for some time and couldn't come up with any solution.
Reduce the number until you only have two digits left: ``` while (n >= 100) n /= 10; ```
This question already has answers here:Closed11 years ago. Possible Duplicate:Floating point comparison When I run the code below I get the following output: Output : if Why does this happen? ``` #include <stdio.h> void main() { float a = 0.7; if(a<0.7) { printf("if"); } else { ...
Your program compares thedoublerepresentation of0.7(which is what the compiler produces when you write0.7in your program) with afloatrepresentation of0.7(which is what variableacontains). The two are not the same, and it just happens that thedoubleone is slightly larger. EDIT:(float)0.7can be represented compactly in...
I an new at working with IPC objects with synchronization purposes for processes and threads. Is there any special way to implement a Monitor in C? (such as semaphores, pipes, sockets, etc.) Is there a special .h file that has a specific object to use here? If not, which is the best way to implement this? Thanks in...
I'd use select, it works pretty much for everything you need:http://linux.die.net/man/2/select Beyond that, I usually use the pthread style functions for mutexes/semaphores, but it's really down to what the task at hand actually is.
Has anyone had any success with libcurl and POP3 with APOP authentication? I had success with the clear authentication but not with APOP since the library sends the USER command almost immediately after making a connection. How do I make libcurl send APOP command and stop it sending USER command?
libcurl currently doesn't support APOP. You need to dive in and make it so!
I copied an example starting with main (t) { So, when compiling with gcc -pedantic I expected at least compalints about- missing return type of main (that one came)- missing type for 't' - nothing, neither with -Wall nor -pedantic. Is this just a bit generous of gcc or is there a default type in the standard? Could...
The standard makes no provision for amainfunction with 1 parameter - it requires two forms, one with 0 and one with 2. Implementations are permitted to allow others. So, GCC is doing something implementation-dependent to allow this, even if you had specified the type. C89 allows parameters with no declared type, def...