question
stringlengths
25
894
answer
stringlengths
4
863
I am learning(just finished) C+Algorithms and am a newbie. I wanted to know if the POSIX Linux API is used on a Mac. Linux has functions like pread pwrite readv writev nftw symlink pipe popen posix_self sigprocmask sigaction (system calls). Does the Mac have the same API?? I heard that OS-X is based on a BSD kernel so...
The Wikipedia article on POSIXhas a section dedicated to compliance. Short answer: yeah, it's going to have all the POSIX functionality you're likely to come up against. And it will probably have more (e.g. a lot of BSD apis that might not actually be POSIX)
I have a double link list that stores some information. When I try and return one of the values inside the link list, I get the warning: function returns address of local variable. This is my return statement: ``` return curr_val->value; ``` value is of typeconst void*. Method signature is like:void *get_val(int ...
The problem is likely that you have assigned the address of a stack-allocated variable tovalue. You need to usenewormallocto get memory for variables you intend to have continue to exist beyond the current stack frame.
15:9: error: incompatible types when assigning to type ‘char[3]’ from type ‘char *’ ``` #include <stdio.h> int main(int argc, char *argv[]) { char servIP[3]; int servPortNum; if(argc<3) { printf("Usage: clientApp servIP servPortNum\n"); } servIP = argv[1]; servPortNum =...
``` strncpy (servIP, argv [1], sizeof (servIP) - 1); servIP [sizeof (servIP) - 1] = 0; ``` But are you sureservIPis big enough for an IP address?
Is there any way for me to run a system command such as date through my C program and pipe the output to a char *date so I can use it later? I've been trying to use the "system" command but doing system("date"); immediately prints out the date output to stdout. I want to grab this data using system or exec within my p...
Take a look atpopen(). You open aFILEpointer with it, like so: ``` #include <stdio.h> FILE *f = popen("date", "r"); ``` And then you can usefread()orfscanf()to read fromfinto your buffer of choice.
I am developing a network application in ANSI C. I would like to use Visual Studio 2008 or 2010 to develop it. I want to embed Lua as a scripting language. I would like suggestions as to whether or not I should compile the application with Lua's sourcecode, or if I should use a .dll. If I should compile with the sou...
You can go down either route. Pretty simple to compile into your code though, just include all the source ( except, you don't need the stuff for the Lua command line tool). Once you've done this, you have access to the API, and away you go!
for example: ``` int *k; void* c=(void*)&k; char* x=(char*)c;//outputs a warning or an error int *g=(int *)c;//compiles successfully(without warnings) int *gg = malloc(sizeof(int)); //compiles successfully(without warnings) ``` is it possible to achieve this with gcc or any other compiler?
The short answer is no. Once you've cast your pointer tovoid*, you've lost all type information. Let's say you pass thevoid*into a function in a different translation unit. When compiling that other translation unit, there is no way for the compiler to validate the semantics of anything you do with that pointer. If ...
Well, i have thislinkand i want to parse through it and get only the joke. Its in json format. I would like to use c or c++, not python because i already did it with python.
Hereis a pretty impressive list of JSON parsers. Take your pick, C and C++ are certainly both supported.
``` int m, n, j; n=16; j=15; m = n++ -j+10; printf("%d", m); ``` Output: 11. Here, first, the old value ofnis given tomand then it is incremented so the new value i get is 17 and then the expression is solved i.e.j+10= 25 then the new value of n is subtracted by 25 i.e 17-25. Am i right ? but the answer doesn't matc...
m = n++ -j+10;is same as ``` m = n -j+10; n = n + 1; // m is 11. ``` If it was++nIt would be ``` n = n + 1; m = n -j+10; //m is 12. ``` then the expression is solved i.e. j+10 = 25 No. It would be-j+10= -5 My suggestion is,dont write complex expression unless you are completely sure what you are writing.
So far i got this. But i am getting this error : "Undefined references to `WinMain@16' " Please help. ``` int sumEvensRecursively(int no1, int no2) { no1=5; no2=20; if (no1 % 2 == 1) { return sumEvensRecursively(no1+ 1, no2); } return no1+ sumEvensRecursively(no1+ 2, no2); } ```
There are several issues wrong: the function is recursive on all control paths, you need a stop condition.it appears you passno1andno2as parameters, yet you assign them values on the next lines. What's the point?the error you're getting is because you're probably compiling on windows, where themain()is declared somet...
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.Closed11 years ago. Kindly give an detailed explanation...
``` return a<b ? a : b ``` is equivalent to ``` if (a<b) return a; else return b; ```
I disassembled an object file (most likely generated using the Visual C++ compiler) usingDumpBinand saw the following piece of code: ``` ... ... mov dword ptr [ebp-4],eax // Why save EAX? push dword ptr [ebp+14h] push dword ptr [ebp+10h] push dword ptr [ebp+0Ch] push ...
Also, maybe it's compiled in release mode, but that variable has been marked asvolatile, which tells the compiler that such variable may change without it knowing, so it is forced to continuously write/restore it on/from the stack
This is part of my first comp sci assignment, we are writing a C program that evaluates several equations. Here is the code that is giving the wonky result: ``` // 1. Newton’s Second Law of Motion printf("Newton's Second Law of Motion \nPlease enter mass and acceleration as decimal-point values separated by a comma (...
Are you using UNICODE? Seems like there's a difference in the apostrophe:Newton’svsNewton's. Did you copy-paste from somewhere?
How can youpracticallytest a synchronized data structure (in C)? Firing a couple of threads and have them compete for access to the structure for a while to see if anything goes wrong doesn't sound very safe. EDIT in response to comments: I mean that there are several threads running functions that operate on the sa...
No-onereally knows how to do this with 100% reliability.Hereis just one example of of a testing tool to find concurrency bugs.
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'm looking to crowd-source this, as I'm having bit of difficulty finding an "industry standard" library for SMTP in C/C++...
My personal favourite isVMime, for C++ only, but the highly reputedlibcurlalso has SMTP support (as well as many other features). VMime has adual license; I think curl has a sort of MIT-style license.
What is the best way to save a file from internet onjavascriptand/orCand/or evenC++? I saw this same question for C# and Java, but nothing to this three languages, so here is the question. Hey, not so easy. The url point to somehttp://xx.xxxx.com/p.php?pid=staticetctectc.... I guess is php code which produce a nice...
You can easily do this with JavaScript using Node.js. Here is a link to an example:http://www.hacksparrow.com/using-node-js-to-download-files.html You could also do it from the command line using wget or curl. They are both available on pretty much every platform you can imagine.
I am implementing a user-space network device that makes use of the LinuxTUN/TAP driver. Is it possible to install a custom ioctl handler? I would like to be able to send custom status queries and control commands to the program. Or perhaps there is a slicker way of doing this?
Have the program listen on another normal socket (AF_LOCAL, AF_INET6, ... non-tun in any case) of your choice.
I have come across some c code where the there is an enum type followed by a function implementation, such as this: ``` enum OGHRet funcX ( OGH *info, void *data, int size ) { /* c code that does stuff here */ } ``` I am confused over how this enum statement works inline with the function implementation. I assum...
its just saying its returning an enum called OGHRet which will be defined elsewhere. Here's a fragment of code that shows enums and functions that return enums side by side... ``` enum Blah { Foo, Bar }; enum Blah TellMeWhy() { return Bar; } ```
In my library I have to return a string to the callers. The string I am returning will be a global array, the intended use from the caller is just to read the string. I don't want them to modify it.. Is this the right way to declare the function.. ``` const char * get_some_details(); ``` This should generate a warn...
Returningconst char*is exactly the right thing to do in these circumstances. Many older APIs don't useconstsince they pre-date the introduction ofconstin C90 (there was noconstbefore then).
I disassembled an object file (most likely generated using the Visual C++ compiler) usingDumpBinand saw the following piece of code: ``` ... ... mov dword ptr [ebp-4],eax // Why save EAX? push dword ptr [ebp+14h] push dword ptr [ebp+10h] push dword ptr [ebp+0Ch] push ...
Also, maybe it's compiled in release mode, but that variable has been marked asvolatile, which tells the compiler that such variable may change without it knowing, so it is forced to continuously write/restore it on/from the stack
This is part of my first comp sci assignment, we are writing a C program that evaluates several equations. Here is the code that is giving the wonky result: ``` // 1. Newton’s Second Law of Motion printf("Newton's Second Law of Motion \nPlease enter mass and acceleration as decimal-point values separated by a comma (...
Are you using UNICODE? Seems like there's a difference in the apostrophe:Newton’svsNewton's. Did you copy-paste from somewhere?
How can youpracticallytest a synchronized data structure (in C)? Firing a couple of threads and have them compete for access to the structure for a while to see if anything goes wrong doesn't sound very safe. EDIT in response to comments: I mean that there are several threads running functions that operate on the sa...
No-onereally knows how to do this with 100% reliability.Hereis just one example of of a testing tool to find concurrency bugs.
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'm looking to crowd-source this, as I'm having bit of difficulty finding an "industry standard" library for SMTP in C/C++...
My personal favourite isVMime, for C++ only, but the highly reputedlibcurlalso has SMTP support (as well as many other features). VMime has adual license; I think curl has a sort of MIT-style license.
What is the best way to save a file from internet onjavascriptand/orCand/or evenC++? I saw this same question for C# and Java, but nothing to this three languages, so here is the question. Hey, not so easy. The url point to somehttp://xx.xxxx.com/p.php?pid=staticetctectc.... I guess is php code which produce a nice...
You can easily do this with JavaScript using Node.js. Here is a link to an example:http://www.hacksparrow.com/using-node-js-to-download-files.html You could also do it from the command line using wget or curl. They are both available on pretty much every platform you can imagine.
I am implementing a user-space network device that makes use of the LinuxTUN/TAP driver. Is it possible to install a custom ioctl handler? I would like to be able to send custom status queries and control commands to the program. Or perhaps there is a slicker way of doing this?
Have the program listen on another normal socket (AF_LOCAL, AF_INET6, ... non-tun in any case) of your choice.
I have come across some c code where the there is an enum type followed by a function implementation, such as this: ``` enum OGHRet funcX ( OGH *info, void *data, int size ) { /* c code that does stuff here */ } ``` I am confused over how this enum statement works inline with the function implementation. I assum...
its just saying its returning an enum called OGHRet which will be defined elsewhere. Here's a fragment of code that shows enums and functions that return enums side by side... ``` enum Blah { Foo, Bar }; enum Blah TellMeWhy() { return Bar; } ```
In my library I have to return a string to the callers. The string I am returning will be a global array, the intended use from the caller is just to read the string. I don't want them to modify it.. Is this the right way to declare the function.. ``` const char * get_some_details(); ``` This should generate a warn...
Returningconst char*is exactly the right thing to do in these circumstances. Many older APIs don't useconstsince they pre-date the introduction ofconstin C90 (there was noconstbefore then).
This question already has answers here:Closed11 years ago. Possible Duplicate:Compute fast log base 2 ceiling What is the fastest possible way to find out how many binary digits a particular integer has when it is converted from decimal to binary in C/C++? Ex. 47(10)= 101111(2) So 47 has 6 digits represented in bi...
For a quick fun way of doing this without needing to call math functions, check this one out: ``` for (digits = 0; val > 0; val >>= 1) digits++; ``` As a bonus, this should cook down to a memory load and 2 registers in use, for extra whiz-bang.
I've heard of a lot of cool GCC extensions and built-in functions over the years, but I always wind up forgetting about them before thinking of using them. What are some cool GCC extensions and built-ins, and some real-life examples of how to put them to use?
GCC provides many features as compiler extensions, off the top of mind and frequently used by me are: Statement ExpressionsDesignated Initializers There are many more documented on the GCC websitehere. Caveat:However, using any form of compiler extensions renders your code non-portable across other compilers so do ...
Given a literal address, how can I determine which section that address falls in? Here is an example. From a disassembly of a program, made with 'objdump', I obtain a literal address 0x8048520: 80483ea: c7 45 f4 20 85 04 08 movl $0x8048520,-0xc(%ebp) ... On my platform (Linux 2.6.39, Gentoo) I can o...
Using your example address of 0x8048520: ``` objdump -s --start-address=0x8048520 --stop-address=0x8048521 elf_file | grep section | awk '{ print $4 }' | cut -d':' -f 1 ``` In your example, the output of this command would be: ``` .rodata ```
I am using waitpid as given waitpid(childPID, &status, WNOHANG); This is used in a program inside an infinite loop that forks when needed and the parent waits for the child process to return. But recently I have come across a problem where in the program exits after printing this to the cerr.. waitpid: No child pro...
I guess what is happening over here is that the fork system call is failing due lo lack of available entries in the process table. You can do a perror on the output of fork. I think it should be RESOURCE_TEMPORARILY_UNAVAILABLE.
How can I "draw"\"merge" a png top of another png (background) using libpng, while keeping the alpha section of the png being drawn on top of the backhround png. There does not seem to be any tutorials or anything mentioned in the documentation about it.
libpng is a library for loading images stored in the PNG file format. It is not a library for blitting images, compositing images, or anything of that nature. libpng's basic job is to take a file or memory image and turn it into an array of color values. What you're talking about is very much out of scope for libpng. ...
Suppose I have one server and one client program. Clients have four options (square root, prime number....etc) and can choose any of them. One Server program provides these four services. I want such a system that: Client's request will accept main server(suppose server.c)main server will call another server for each...
The front-end server will need to parse enough of an incoming request packet to determine the type of request, then build a new packet passing the parameter(s) through to the appropriate server for that type of request. When it receives an answer back, it'll pass it along to the client (possibly after doing some refor...
I have a zigbee usb dongle that plugs into the usb port on my Windows laptop. I need to be able to capture the incoming packets. I am trying to write a c program that will capture the incoming packets by monitoring the bus associated with the corresponding usb port. Are there some c libraries that facilitate this mo...
This is what a hardware driver does for you: it monitors low-level hardware directly, and then processes and exposes that data to user-level programs in a more convenient interface. I thinkTelegesisandAdaptiveoffer Windows drivers for download; whoever manufactured your Zigbee should provide drivers of their own, if ...
I'm getting a list of files on a linux-like system using opendir/readdir. It appears that the directory entries are returned in alphabetical order of file name. However, I don't see anything in the man pages about this order being guaranteed. Can anyone tell me whether or not readdir guarrantees an order?
Thereaddirmethod doesn't guarantee any ordering. If you want to ensure they are sorted alphabetically you'll need to do so yourself. Note: I searched for a bit for definitive documentation saying this is the case. The closest I came is the following link http://utcc.utoronto.ca/~cks/space/blog/unix/ReaddirOrder I...
I'm not quite sure if it is really necessary to have prototypes for static functions in C. As long as I'm not exporting such functions (i.e. they don't have external linkage), what other benefit can this give? Thanks.
To cite some authority, MISRA-C:2004 rule 8.1 enforces prototypes for functions with external linkage, but also mentions internal linkage: "The provision of a prototype for a function with internal linkage is good programming practice." I take it this is good practice because it makes your coding style between int...
I preload some lua file withluaL_loadfileand then I execute it multiple timest (it's a server). I have somedofile()calls in the lua file. WillluaL_loadfilealso preload alldofile()within the lua file?
No,luaL_loadfiledoes not executeanycode in the file, In particular, it does not call any embeddeddofile()orrequireor any other function call.
I'm using SQLite with C API. On C API, I can check the result value of a column withsqlite3_column_*functions. the problem is there is no function for the case of the value isNULL. Of course, I can check the value withsqlite3_column_bytesfunction, but it can cause conversion, and I want to avoid conversion at all. Ho...
From what I can remember (and tell from the documentation), the correct way to do it is to usesqlite3_column_type()to check forSQLITE_NULL. Just be sure to do it before doing anything that may cause conversion of the column.
I'm doing a homework assignment in which I need to print out to the console and a text file the numbers 0-255 along with the Hex and Ascii which goes along with them. The main focus of the assignment is to learn about formatting and file handling. I've figured out all the nice formatting by using widths and I can pr...
You'll need to filter out things you don't want to print yourself. To help with that, look into theisgraphand the otheris*functions. They should help you along pretty well.
I was able to make my app go full screen, but I can't make it go back to the windowed mode withborders visible. I tried to call XDeleteProperty to clear out the settings for full screen but it doesn't seem to work.
If you're using _NET_WM_STATEhttp://standards.freedesktop.org/wm-spec/latest/ar01s05.html#id2569140then prior to mapping the window you set the property, but after mapping the window you have to send a client message and the window manager updates the property. Read the part of EWMH that starts "To change the state of...
I'm familiar with only one compile time operator in C -sizeof. Are there any others that I as a programmer should be aware of?
Onlysizeofthat I'm aware, although in C99 sizeof cannot be done at compile time for variable length arrays (VLAs).
I am trying to understand why the following statement works: ``` putchar( 1 + '0' ); ``` It seems that the + '0' expression converts the literal to the respective ASCII version (49 in this particular case) that putchar likes to be given. My question was why does it do this? Any help is appreciated. I also apologize...
This has nothing to do with ASCII. Nobody even mentioned ASCII. What this code does assume is that in the system's character encoding all the numerals appear as a contiguous range from'0'to'9', and so if you add an offset to the character'0', you get the character for the corresponding numeral. All character encodin...
I'm currently building a console app for a school project and I really need this function for my app. How do I save all the text from console to a string in C (Windows platform)? For example: If I used the functionsystem("dir"), it will output to console and list all the subdirectories and files in a directory. And...
You could usepopen()rather thansystem(): ``` #include <stdio.h> #include <limits.h> int main() { FILE *fp; char path[PATH_MAX]; fp = popen("DIR", "r"); if (fp == NULL) { /* Handle error */ } while (fgets(path, PATH_MAX, fp) != NULL) { printf("%s", path); } p...
There doesn't seem to be a question for this, and it seems strange that I don't know this. When I program in c/objective-c, must I escape single quotes nested within double quotes. example "'"or"''" is this needed "\'"or"\'\'" thanks
No, escaping is unnecessary for single-quotes.
I need a little help with my new assignment.Problem: Given Two Linked List representation of a decimal numbers(238 & 35):-2->3->8 and,3->5Add elementsso that your Final Linked List must be 2->7->3. What could be the best approach to solve this problem.
Without doing your homework for you - I think the best general approach would be to break it into three steps. Reverse both the lists.Add the elements pairwise, carrying a one where necessary.Reverse the resulting list. Since step 1 and step 3 are kind of the same, you probably want to write a separate function for ...
I am Just a begineer in C Programming. While solving a programming assignement I came across the need to convert an array ofunsigned chartointeger. For Example: ``` unsigned char x[]="567"; unsigned char y[]="94"; ``` Now I have to add the integer values in bothxandy. That is: ``` int sum=661; ``` What is the sim...
You're looking foratoi().
I'm trying to compile open source tool "abc". When I tried to build the solution file, I got a lot of error messages. The c source code has include directive, and VS2010 cannot find the header files. The file structure is as follows. ``` #include "src/misc/util/abc_global.h" #include "pr.h" ``` In project prop...
I needed to setup properties in C/C++/General/Additional Include Directories
I am trying to wrap a C library with Ruby-FFI. However, the function names from the library start with capital letters. As a result, it seems as if ffi is trying to generate constants, and when you try access them at runtime from Ruby, you get an error saying ``` NameError: uninitialized constant (name of function) `...
Wait, it seems that an example is shown here:https://github.com/ffi/ffi/wiki/Windows-Examples What they do here is the following: ``` attach_function :message_box, :MessageBoxW, [ :pointer, :buffer_in, :buffer_in, :int ], :int ``` So it seems that attach_function allows you to pass the alias as the first parameter,...
What is the difference between memory indirect call and register indirect call? I'm trying to learn something about linux rootkit detection, how can I recognize such calls in disassembled memory? How do they look in C language before compiling?
An indirect branch is a branch where the branch is made to an address that is stored in a register or in a memory location. The operand of the branch instruction is the register or the memory location that stores the address to branch. See wikipedia page for more information:http://en.wikipedia.org/wiki/Indirect_bran...
How can I get the actual "username" without using the environment (getenv, ...) in a program? Environment is C/C++ with Linux.
The functiongetlogin_r()defined inunistd.hreturns the username. Seeman getlogin_rfor more information. Its signature is: ``` int getlogin_r(char *buf, size_t bufsize); ``` Needless to say, this function can just as easily be called in C or C++.
Xlib has a function calledXAllocSizeHintsto allocate aXSizeHintsstructure on the heap and set it to zero. ``` XSizeHints *sizehints; sizehints=XAllocSizeHints(); ``` However, is it necessary to always use this function? Or can I do this: ``` XSizeHints sizehints; memset(&sizehints, 0, sizeof(XSizeHints)); ``` I wo...
It's fine to stack allocate these (as long as you don't keep them around after the current function returns of course). There's no magic in those alloc functions. In fact most code probably does allocate them on the stack.
Currently, I'm reading the CTS and DSR signals of a serial port in the following way: ``` bool get_cts(int fd) { int s; ioctl(fd, TIOCMGET, &s); return (s & TIOCM_CTS) != 0; } ``` Now I'd like to wait untilget_cts()returns true. A simple loop isn't the best solution I think (as it's extremely resource-in...
There is the ioctlTIOCMIWAITwhich blocks until a given set of signals change. Sadly this ioctl is not documented in thetty_ioctl(4)page nor inioctl_list(4). I have learned about this ioctl in this question: Python monitor serial port (RS-232) handshake signals
In C you have the"%c"and"%f"formats flags forprintf- andscanf-like functions. Both of these function use variable length arguments..., which always convertfloatstodoublesandcharstoints. My question is, if this conversion occurs, why do separate flags forcharandfloatexist? Why not just use the same flags as forintandd...
Because the way it gets printed out is different. ``` printf("%d \n",100); //prints 100 printf("%c \n",100); //prints d - the ascii character represented by 100 ```
I know this is a simple one, still I'm too sleepy to figure it out. Can someone help me? ``` char buf1[] = "one second program started\n"; char buf2[] = "one second program end\n"; int main(void) { write(1,buf1,100); sleep(1); write(1,buf2,100); } ``` I need the first statement printed, then after a unit wait,...
Change100tostrlen(buf1)orstrlen(buf2).
We have some old C code with pre-ANSI (K&R-style) function declarations. For example: ``` int foo(x, y) double x, y; { /* do some stuff */ } ``` Is there a compiler switch to enable support for this in Visual C++ 2008?
In order to get this to compile put the code in a .c file vs. a .cpp. This instructs Visual Studio to compile the code as C instead of C++
I'm doing a homework assignment in which I need to print out to the console and a text file the numbers 0-255 along with the Hex and Ascii which goes along with them. The main focus of the assignment is to learn about formatting and file handling. I've figured out all the nice formatting by using widths and I can pr...
You'll need to filter out things you don't want to print yourself. To help with that, look into theisgraphand the otheris*functions. They should help you along pretty well.
I was able to make my app go full screen, but I can't make it go back to the windowed mode withborders visible. I tried to call XDeleteProperty to clear out the settings for full screen but it doesn't seem to work.
If you're using _NET_WM_STATEhttp://standards.freedesktop.org/wm-spec/latest/ar01s05.html#id2569140then prior to mapping the window you set the property, but after mapping the window you have to send a client message and the window manager updates the property. Read the part of EWMH that starts "To change the state of...
I'm familiar with only one compile time operator in C -sizeof. Are there any others that I as a programmer should be aware of?
Onlysizeofthat I'm aware, although in C99 sizeof cannot be done at compile time for variable length arrays (VLAs).
I am trying to understand why the following statement works: ``` putchar( 1 + '0' ); ``` It seems that the + '0' expression converts the literal to the respective ASCII version (49 in this particular case) that putchar likes to be given. My question was why does it do this? Any help is appreciated. I also apologize...
This has nothing to do with ASCII. Nobody even mentioned ASCII. What this code does assume is that in the system's character encoding all the numerals appear as a contiguous range from'0'to'9', and so if you add an offset to the character'0', you get the character for the corresponding numeral. All character encodin...
I'm currently building a console app for a school project and I really need this function for my app. How do I save all the text from console to a string in C (Windows platform)? For example: If I used the functionsystem("dir"), it will output to console and list all the subdirectories and files in a directory. And...
You could usepopen()rather thansystem(): ``` #include <stdio.h> #include <limits.h> int main() { FILE *fp; char path[PATH_MAX]; fp = popen("DIR", "r"); if (fp == NULL) { /* Handle error */ } while (fgets(path, PATH_MAX, fp) != NULL) { printf("%s", path); } p...
There doesn't seem to be a question for this, and it seems strange that I don't know this. When I program in c/objective-c, must I escape single quotes nested within double quotes. example "'"or"''" is this needed "\'"or"\'\'" thanks
No, escaping is unnecessary for single-quotes.
I need a little help with my new assignment.Problem: Given Two Linked List representation of a decimal numbers(238 & 35):-2->3->8 and,3->5Add elementsso that your Final Linked List must be 2->7->3. What could be the best approach to solve this problem.
Without doing your homework for you - I think the best general approach would be to break it into three steps. Reverse both the lists.Add the elements pairwise, carrying a one where necessary.Reverse the resulting list. Since step 1 and step 3 are kind of the same, you probably want to write a separate function for ...
I am Just a begineer in C Programming. While solving a programming assignement I came across the need to convert an array ofunsigned chartointeger. For Example: ``` unsigned char x[]="567"; unsigned char y[]="94"; ``` Now I have to add the integer values in bothxandy. That is: ``` int sum=661; ``` What is the sim...
You're looking foratoi().
I'm trying to compile open source tool "abc". When I tried to build the solution file, I got a lot of error messages. The c source code has include directive, and VS2010 cannot find the header files. The file structure is as follows. ``` #include "src/misc/util/abc_global.h" #include "pr.h" ``` In project prop...
I needed to setup properties in C/C++/General/Additional Include Directories
I am trying to wrap a C library with Ruby-FFI. However, the function names from the library start with capital letters. As a result, it seems as if ffi is trying to generate constants, and when you try access them at runtime from Ruby, you get an error saying ``` NameError: uninitialized constant (name of function) `...
Wait, it seems that an example is shown here:https://github.com/ffi/ffi/wiki/Windows-Examples What they do here is the following: ``` attach_function :message_box, :MessageBoxW, [ :pointer, :buffer_in, :buffer_in, :int ], :int ``` So it seems that attach_function allows you to pass the alias as the first parameter,...
What is the difference between memory indirect call and register indirect call? I'm trying to learn something about linux rootkit detection, how can I recognize such calls in disassembled memory? How do they look in C language before compiling?
An indirect branch is a branch where the branch is made to an address that is stored in a register or in a memory location. The operand of the branch instruction is the register or the memory location that stores the address to branch. See wikipedia page for more information:http://en.wikipedia.org/wiki/Indirect_bran...
How can I get the actual "username" without using the environment (getenv, ...) in a program? Environment is C/C++ with Linux.
The functiongetlogin_r()defined inunistd.hreturns the username. Seeman getlogin_rfor more information. Its signature is: ``` int getlogin_r(char *buf, size_t bufsize); ``` Needless to say, this function can just as easily be called in C or C++.
Xlib has a function calledXAllocSizeHintsto allocate aXSizeHintsstructure on the heap and set it to zero. ``` XSizeHints *sizehints; sizehints=XAllocSizeHints(); ``` However, is it necessary to always use this function? Or can I do this: ``` XSizeHints sizehints; memset(&sizehints, 0, sizeof(XSizeHints)); ``` I wo...
It's fine to stack allocate these (as long as you don't keep them around after the current function returns of course). There's no magic in those alloc functions. In fact most code probably does allocate them on the stack.
Is there a difference how a processor executes a background or foreground process or how operating system deals with their scheduling. If there is no difference at processor level between background and foreground job then at which level the difference comes ?
Creating a new background process in shell has nothing to do with the way the processor executes it. Only difference is that the shell does not wait for a background process to finish. Code for a process creation :1) fork a process2) if (& symbol is present at the end of command)continue to accept new commandelsewait...
I have usedexit()to terminate the process. I do not have any exit handlers registered also I do not care about flushing buffers on exit, so thought of using_exit()as more robust method to terminate process. The only question is, does_exit()handles closing of all open file descriptors and open sockets gracefully?
The functionexitcalls_exit. From TLPI: The following actions are performed by exit():Exit handlers are calledThe stdio stream buffers are flushedThe _exit() system call is invoked Thestandard page for _exitsays this: All of the file descriptors, directory streams, conversion descriptors, and message catalog descr...
Could someone please explain how to correctly allocate memory for for a pointer to an array of pointer of characters in c? For example: ``` char *(*t)[]; ``` I try to do it like this: ``` *t = malloc( 5 * sizeof(char*)); ``` This gives me a compile error: ``` error: invalid use of array with unspecified bounds ``...
What you can do is: ``` char **t = (char**)malloc( <no of elements> * sizeof(char*)); ``` That allocates the array of pointers. ``` for (i = 0 ; i< <no of elements> ; i++) { t[i] = (char*)malloc( <length of text> * sizeof(char)); } ``` That allocates memory for the text that each element of the array points to...
When creating a pointer array in c what does the effect of adding parentheses do? For example int (*poi)[2]; vs int *poi[2];
Pointer to an array of 2ints: ``` int (*poi)[2]; ``` An array of twointpointers: ``` int *poi[2]; ``` Normally Array has higher precedence than the pointer, but if you add the parentheses then the pointer comes "first".
So I've got this simple code in C. ``` if (flags & 4) ``` Now when I port the line to java: ``` if ((flags & 4) == 1) ``` It doesn't trigger. Whats the correct way to port the C code to Java? What am I doing wrong with the & operator?
It should be!= 0rather than== 1: ``` if ((flags & 4) != 0) ``` The reason for this is that in C anything that is not zero is consideredtruein anifstatement, while Java forces you to use Booleans. In this case, the expression can evaluate either to 4 or to 0, so comparing it with 1 is always false.
Can you detect whether or not a debugger is attached to your native Windows process by using a high precision timer to time how long it takes to divide an integer by zero? The rationale is that if no debugger is attached, you get a hard fault, which is handled by hardware and is very fast. If a debugger is attached, ...
Since there is absolutely nothing you can do to prevent a determined person from reverse engineering your code, no clever approach you find will be significantly better than callingIsDebuggerPresent()
Is it possible to emulate object methods in C? I'd like to be able self-reference a structure as a parameter to a member function argument e.g.: ``` struct foo { int a; int (*save)(struct foo *); }; int save_foo(struct foo *bar) { // do stuff. } struct foo * create_foo() { struct foo *bar = malloc(s...
No, this is not possible. There are object-oriented libraries in C, but they pass the "this" object to the "method" explicitly as in ``` bar->save(bar); ``` See the Berkeley DB C API for an example of this style, but do consider using C++ or Objective-C if you want to do OO in a C-like language.
I am using pre-compiled headers in my project in C but we are integrating a .CPP file into the project. Here's the error: ``` Error 1 fatal error C1853: 'Debug\MuffinFactory.pch' precompiled header file is from a previous version of the compiler, or the precompiled header is C++ and you are using it from C (or ...
So don't use precompiled headers for that single file! Being a .cpp file, it will have separate compilation options anyway.
X is true nearly 99.9% of the time but I need to handle Y and Z as well. Although the body of the X condition is empty, I'm thinking it should be faster than potentially checking 2 other conditions Y and Z if the X condition is omitted. What do you think? ``` if (likely(X)) { } else if (unlikely(Y)) { ... } else if ...
You might want to know what exactly happens when you use likely or unlikely:http://kerneltrap.org/node/4705 I would personally write ``` if (unlikely(!X)) { if (unlikely(Y)) { ... } else if (unlikely(Z)) { ... } } ``` Which means ifx, continue execution, elsejumpto if body.
Could someone please show me a minimal working example of using C language for Cairo with Gtk3 to draw a single line in aGtkDrawingArea. I've tried to modifytestcairo.cin the Gtk3 tests folder but I can't get it to work. Please don't suggest the tutorials at the Cairo site; Zetcode.com or gnome.org which are either no...
I got it. The key difference is that for gtk+3 you must draw from within a "draw" signal handler. With gtk+2 it's from within the "expose-event" signal handler. Here's aminimal working example.
Does the two code snipets below do exactly the same thing? ``` do { Delay_us(1); status = fetchStatus(); }while(!status); ``` Second snipet -> ``` do { Delay_us(1); }while(status = fetchStatus(), !status); ``` which is preferable?
You can do: ``` do { Delay_us(1); } while( !fetchStatus() ); ``` That way you do not need to create a local variable if youdo notuse it.
I have an algorithm that takes 7 days to Run To Completion (and few more algorithms too) Problem: In order to successfully Run the program, I need continuous power supply. And if out of luck, there is a power loss in the middle, I need to restart it again. So I would like to ask a way using which I can make my prog...
You can separate it in some source files, and use make.
I am just learning some pointers stuff in C and I happened to learn that using the * one can dereference the pointer. So I wrote the following code to check for that. ``` #include<stdio.h> #include<string.h> char *findChar(char *s, char c){ while(*s!=c){ s++; } return s; } int main(){ char myChar='a'; ...
The following is incorrect: ``` char temp = *location; printf(temp); ``` If you want to print out the char, use the following: ``` char temp = *location; printf("%c\n", temp); ``` The first argument toprintf()should be the format string.
I executed this code after compiling in codeblocks:- ``` #include <stdio.h> int main() { char arr[]="HELLO"; int a=arr; return printf("...%s ,%s\n",arr,&a+1); } ``` I got this output:- ...HELLO,HELLO when I changed&atoa,printf returned -1. I am not able to sort out this address logic ,please help...
You are tellingprintfto expect a string, but you are giving it the address of anint(&a). This invokesundefined behaviour, so anything could happen. [In practice, what's probably happening is that the compiler placesadirectly belowarron the stack. So&a+1ends up equal in value to&arr.printfthen reinterprets that addr...
Does C have scope hiding? For example, if I have a global variable: ``` int x = 3; ``` can I 'declare' inside a function or main 'another' int x?
Yes, that's how C works. For example: ``` int x; void my_function(int x){ // this is another x, not the same one } void my_function2(){ int x; //this is also another x { int x; // this is yet another x } } int main(){ char x[5]; // another x, with a different type } ```
I have a function that recieves a pointer to dynamic array of 100 ints. But instead of 100 I have just 50 allocated by malloc or calloc before that. Is there a way that I could check if any ellement (like 79th for example) is allocated rather than wonder what this SIGSEGV actually means ? My question is purely theor...
No, the pointer does not store its size. You may be better off storing the size and the pointer in a struct and passing it instead: ``` typedef struct { size_t size; int *ptr; } my_data; ``` ``` void myFunc(my_data *data) { size_t i; for(i = 0; i < data->size; i++) { // data->ptr[i]; ...
How can I upload (very) large file with HTTP protocol in C (or C++)? I know it's not the right way to upload huge files, but that's not the point. I've already seen sources about POST transfers of files in C++ but I noticed that, each time, the WHOLE binary file was included inside the POST sequence (between "--boun...
You may use "Content-Range" header in HTTP POST request, to upload a slice of a huge file. ``` POST http://[server_ip]:80/upload?fn=xx.dat HTTP/1.1 Content-Range: bytes=0-4095 Content-Type: application/octet-stream Content-Length: 4096 ...... ```
For functions registered usingatexit(): Is it possible to retrieve references to them, to call them directly? Although this is meant as a general question, solutions regarding the use ofgcc/glibcare welcome.
Not in any portable way, no. The list of registered functions is owned by the runtime library, and there is no interface to access it. For glibc specifics as per your comment, the exit handlers are implemented byexit.candexit.h. I haven't studied them intensely enough to figure out of it's possible to drill through t...
I need to convert a formated data to struct like this: ``` struct header { int a; int b; char c; } ``` I have to do it manually like this: ``` [data getBytes:&h.a range:(NSRange){0,4}]; [data getBytes:&h.b range:(NSRange){4,4}]; [data getBytes:&h.c range:(NSRange){8,2}]; ``` Is there a better way to c...
``` [data getBytes:&h range:(NSRange){0, sizeof(struct header)}]; ```
Is there any way to convert ".so" file into source code or some in readable format.
Source code is probably hard, since the .so doesn't "know" which language it was written in. But you can browse around in the assembly code by doing something like this: ``` $ objdump --disassemble my_secret.so | less ```
I want to use distinct function in users collection. In mongo shell, I can use like the following: ``` db.users.distinct("name"); ``` where name is the collections field used to distinct. likewise I want, the same in c code. Only the distinct part I want, familiar with creating connections, working cursors, working...
Seems like you can do that using themongo_run_commandfunction, sincedistinctis acommand:db.runCommand( { distinct: 'users', key: 'name' } )
I have searched for the usage of conditional statements(<,>,<=,etc..,) in C API documentation in the linkhttp://api.mongodb.org/c/current/. But I am unable to find it. Example: The mongo shell query is ``` db.users.find({age: {$gt: 3}}, {}) ``` I want the equivalent C statement for the above.
For example, query: ``` find({ age : { $gt : 5, $lt : 12}}) ``` would be written like this: ``` bson_init(&b); bson_append_start_object(&b,"age"); bson_append_int(&b,"$gt",5); bson_append_int(&b,"$lt",12); bson_append_finish_object(&b); bson_finish(&b); ```
I am working under Linux, with two physical ethernet interfaces. I have grouped the two interfaces to a bonding interface for backup... and it works. I would like to know if there is any way to know, from my C user program, what is the active interface. Thanks
Look at/sys/class/net/bond0/bonding/active_slaveand read it using a program or code of your choice. (Replace path accordingly if using an interface name different frombond0.)
I was reading android source code in that I am not getting what doesOPEN GL ESlibrary do and what doesEGL librarydo.? Is there any relationship between this two libraries? I have looked athttp://www.khronos.org/opengles/documentation/opengles1_0/html/but still not getting.
EGL is the interface between OpenGL ES and the underlying native display platform. It is used to create & manage rendering surfaces & graphics contexts.
Could someone please show me a minimal working example of using C language for Cairo with Gtk3 to draw a single line in aGtkDrawingArea. I've tried to modifytestcairo.cin the Gtk3 tests folder but I can't get it to work. Please don't suggest the tutorials at the Cairo site; Zetcode.com or gnome.org which are either no...
I got it. The key difference is that for gtk+3 you must draw from within a "draw" signal handler. With gtk+2 it's from within the "expose-event" signal handler. Here's aminimal working example.
Does the two code snipets below do exactly the same thing? ``` do { Delay_us(1); status = fetchStatus(); }while(!status); ``` Second snipet -> ``` do { Delay_us(1); }while(status = fetchStatus(), !status); ``` which is preferable?
You can do: ``` do { Delay_us(1); } while( !fetchStatus() ); ``` That way you do not need to create a local variable if youdo notuse it.
I have an algorithm that takes 7 days to Run To Completion (and few more algorithms too) Problem: In order to successfully Run the program, I need continuous power supply. And if out of luck, there is a power loss in the middle, I need to restart it again. So I would like to ask a way using which I can make my prog...
You can separate it in some source files, and use make.
I am just learning some pointers stuff in C and I happened to learn that using the * one can dereference the pointer. So I wrote the following code to check for that. ``` #include<stdio.h> #include<string.h> char *findChar(char *s, char c){ while(*s!=c){ s++; } return s; } int main(){ char myChar='a'; ...
The following is incorrect: ``` char temp = *location; printf(temp); ``` If you want to print out the char, use the following: ``` char temp = *location; printf("%c\n", temp); ``` The first argument toprintf()should be the format string.
I executed this code after compiling in codeblocks:- ``` #include <stdio.h> int main() { char arr[]="HELLO"; int a=arr; return printf("...%s ,%s\n",arr,&a+1); } ``` I got this output:- ...HELLO,HELLO when I changed&atoa,printf returned -1. I am not able to sort out this address logic ,please help...
You are tellingprintfto expect a string, but you are giving it the address of anint(&a). This invokesundefined behaviour, so anything could happen. [In practice, what's probably happening is that the compiler placesadirectly belowarron the stack. So&a+1ends up equal in value to&arr.printfthen reinterprets that addr...
Does C have scope hiding? For example, if I have a global variable: ``` int x = 3; ``` can I 'declare' inside a function or main 'another' int x?
Yes, that's how C works. For example: ``` int x; void my_function(int x){ // this is another x, not the same one } void my_function2(){ int x; //this is also another x { int x; // this is yet another x } } int main(){ char x[5]; // another x, with a different type } ```
I have a function that recieves a pointer to dynamic array of 100 ints. But instead of 100 I have just 50 allocated by malloc or calloc before that. Is there a way that I could check if any ellement (like 79th for example) is allocated rather than wonder what this SIGSEGV actually means ? My question is purely theor...
No, the pointer does not store its size. You may be better off storing the size and the pointer in a struct and passing it instead: ``` typedef struct { size_t size; int *ptr; } my_data; ``` ``` void myFunc(my_data *data) { size_t i; for(i = 0; i < data->size; i++) { // data->ptr[i]; ...
How can I upload (very) large file with HTTP protocol in C (or C++)? I know it's not the right way to upload huge files, but that's not the point. I've already seen sources about POST transfers of files in C++ but I noticed that, each time, the WHOLE binary file was included inside the POST sequence (between "--boun...
You may use "Content-Range" header in HTTP POST request, to upload a slice of a huge file. ``` POST http://[server_ip]:80/upload?fn=xx.dat HTTP/1.1 Content-Range: bytes=0-4095 Content-Type: application/octet-stream Content-Length: 4096 ...... ```
For functions registered usingatexit(): Is it possible to retrieve references to them, to call them directly? Although this is meant as a general question, solutions regarding the use ofgcc/glibcare welcome.
Not in any portable way, no. The list of registered functions is owned by the runtime library, and there is no interface to access it. For glibc specifics as per your comment, the exit handlers are implemented byexit.candexit.h. I haven't studied them intensely enough to figure out of it's possible to drill through t...