mardi 4 août 2015

need help for improving my snake game in C

Its not a programming help

There is a gap coming in the snake body while moving top and bottom , I tried my part and found that its due to console fixed character width in Microsoft OS . can we overcome this in any way ... Please don't say "go for GUI".

Here's the video link



via Chebli Mohamed

Threads creation in C

void print_hello_world() {
    pid_t pid = getpid();
    printf("Hello world %d\n", pid);
    pthread_exit(0);
}

void main() {
    pthread_t thread;
    pthread_create(&thread, NULL, (void *) &print_hello_world, NULL);
    print_hello_world();
}

I really couldn't understand what is the need of (void *) in pthread_create. And do we need "&print_hello_world" in the same or could drop "&" as I have read somewhere that while passing function pointers we don't need to place "&" before the function name.



via Chebli Mohamed

How to convert c program to fully portable for ios

I wrote a simple c program for connect to ldap server using opelLdap c library. now I want to run that c program on ios device. but when I move that c program to xcode project it says ldap.h is missing. ldap.h file is saved in standard include file location so it include this way #include <ldap.h> but I move this file to my xcode project and include it this way #include "ldap.h" it generate so many error because this ldap.h header file contain lot of other standard header files and they have their own dependencies and so on. they all are include this way #include <header.h> it is not possible to convert all the <> to " " one by one. is there any way to to this thing. actually I need to move my code with it's all dependencies I am new to both of this c and xcode(swift/objective-c)



via Chebli Mohamed

Xlib difference between _NET_ACTIVE_WINDOW and XGetInputFocus

What's the difference between _NET_ACTIVE_WINDOW and XGetInputFocus() ? Do they always point to the same window? When use one over the other?

Thanks.



via Chebli Mohamed

C Programming - fprintf and printf in while cicle doesn't work

I'm getting a strange problem with a while cicle inside of a function.

I have to look for the extreme vertices of a .ply model. All the data is stored in a linked list. When I'm done creating the list, I call the findExtremeVertex function, that modifies 6 global variables (leftVertex, rightVertex, downwardVertex, upwardVertex, backVertex and frontVertex).

To see if the values are right (the models I use are a bit too big to control every single line to find the maximum of every vertex) I decided to print every change in the max-min values but, when I try to print them in a file, the file is empty. Why is that? Also, when I saw that the file was empty, I tried to print something directly in the console but that didn't work either.

Here's the code of the funcion:

void findExtremeVertex(Vertex *vertex){
    FILE *modelInfoFile;
    int i = 0;

    ///Giving data to direction-vertices pointers
    leftVertex = malloc(sizeof(Vertex));
    rightVertex = malloc(sizeof(Vertex));
    upwardVertex = malloc(sizeof(Vertex));
    downwardVertex = malloc(sizeof(Vertex));
    frontVertex = malloc(sizeof(Vertex));
    backVertex = malloc(sizeof(Vertex));

    ///Giving the direction-vertices the values of the parameter
    leftVertex = vertex;
    rightVertex = vertex;
    upwardVertex = vertex;
    downwardVertex = vertex;
    frontVertex = vertex;
    backVertex = vertex;

    ///Opening file
    modelInfoFile = fopen(us2, "w");
    if(modelInfoFile == NULL){
        printf("Error in file opening. Exiting.");
        exit(EXIT_FAILURE);
    }

    ///Scrolling the list
    while(vertex->prev != NULL){
        vertex = vertex->prev;

        ///If the given element of the list is more to the right than the global variable,
        ///I assign the values of the element to the global variable
        if(vertex->vertexCoordinates.x > rightVertex->vertexCoordinates.x){
            rightVertex = vertex;
        }

        /**
            I'm omitting the other if constructs because are basically
            the same, but the syntax is correct
        **/

        ///Printing in file the cycle information
        fprintf(modelInfoFile, "********** CYCLE %d **********\n\n", i);
        fprintf(modelInfoFile, "Vertex sx\n");
        fprintf(modelInfoFile, "%1.4f %1.4f %1.4f %1.4f %1.4f %1.4f\n\n", leftVertex->vertexCoordinates.x,
                                                                      leftVertex->vertexCoordinates.y,
                                                                      leftVertex->vertexCoordinates.z,
                                                                      leftVertex->vertexNormals.x,
                                                                      leftVertex->vertexNormals.y,
                                                                      leftVertex->vertexNormals.z);

        /**
            Again, I'm omitting some repetitions but the syntax is correct
        **/
        }
    }

I call this function in another function, but there's no segmentation fault signal, the compiler doesn't tell me anything, the program doesn't crash. I have no clue of the error, except from the fact that the file where I print the infos about the cycles is empty. What am I doing wrong?



via Chebli Mohamed

I'm copying printf code from word, but the quotation marks don't work

So I'm currently doing a reasonably big program, and I need to add in some images. I decided to do this by way of ascii art, so I converted my image, stuck it in word, and using aragrah points and find and replace I stuck 'printf("' at the start of each line, and '\n)"' at the end.

The problem I'm facing is that the " don't work, and considering I've got literally thousands to do before my program has the amount of art it needs, I could really use some help on how to fix them without manually changing them.



via Chebli Mohamed

Tiny Linked List error in C

I have this four files,

tinyll.c tinyll.h in /home/user/lib

test.c tinyll.h in /home/user/code

and compile with this instructions for create a static library libtinyll.a and use it.

; in lib
$ gcc -c tinyll.c
$ ar -cvq libtinyll.a *.o

; in code
$ gcc -o test test.c ../lib/libtinyll.a

Until here all is ok. But I don't know why I obtain segmentation fault because the lines from [CODE ERROR] but showElements work. The target is not pass code from test.c to tinyll.c for treat the tiny list linked. How fix that?

/////////////////////////////////// test.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "tinyll.h"

int main(int argc, char *argv[])
{    
    progname = argv[0];

    char *file = "fwords";
    int n;
    PTLL lsone = NULL;
    n = loadfileinTLL(file,&lsone);

    // work. good. 
    showElements(lsone);

    // [CODE ERROR]
    // Why here dont work?
    // segmentation fault, load the first word
    // but in the second crash.
    while (lsone != NULL) {
        printf("%s",lsone->word);
        lsone = lsone->next;
    }    
    return 0;
}

/////////////////////////////////// tinyll.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "tinyll.h"

void addElement(PPTLL lst, char data[])
{
    PTLL elemt;
    elemt = (PTLL) malloc(sizeof(TLL));

    if (elemt == NULL) {
        fprintf(stderr, "%s: insufficient memory.\n", progname);
        exit(1);    
    }

    if (*lst == NULL)
    {
        strncpy(elemt->word, data, 45);
        elemt->next = NULL;
        *lst = elemt;
    }
    else {
        // add in front of list
        strncpy(elemt->word, data, 45);
        elemt->next = *lst;
        *lst = elemt;
    }
}

void showElements(PTLL lst)
{
    while (lst != NULL) {
        printf("%s\n",lst->word);
        lst = lst->next;
    }
}

int loadfileinTLL(char *filepath, PPTLL plst) 
{
    FILE *f;
    if ((f = fopen(filepath, "r")) == NULL) {
        fprintf(stderr, "%s: error to load file %s.\n", progname, filepath);
        exit(1);
    }

    char buf[45]; int n=0;
    while (fgets(buf,sizeof(buf),f) != NULL) {
        char *nl;
        if ((nl = strchr(buf,'\n')) != NULL) {
            *nl = '\0';
        }
        addElement(plst,buf);
        n++;
    }

    fclose(f);

    return n;
}

//////////////////////////////////// tinyll.h

#include <stdio.h>
#include <stdlib.h>

#ifndef _TINYLL_
#define _TINYLL_

struct list {
    char word[45];
    struct list *next;
};

// Tiny Linked List
typedef struct list TLL;
typedef struct list *PTLL;
typedef struct list **PPTLL;
char *progname;

#endif



via Chebli Mohamed

Choose a C binary according to the enviroment

I have compiled my code with specific flags (-Os, -O2, -march=native and their combinations) in order to produce a faster execution time.

But my problem is that I don't run always in the same machine (because in my lab there are several different machines). Sometimes I run within a MacOS, or within a Linux (in both cases with different OS versions).

I wonder if there is a way to determine which binary will be run depending on the environment where the binary will run (I mean cache size, cpu cores, and other properties about the specific machine)?. In other words, how to choose (when the program loads) the faster binary (previously compiled with different target binary sizes and instruction-set extensions) according to the specific machine used?

Thanks in advance.



via Chebli Mohamed

sscanf hex ints into array of ints vs. unsigned chars

I am converting a string representation of a mac address into an array of UINT8s defined as unsigned char. I am curious why sscanf() will read all 0s when I read into an array of UINT8s and actual values when I read into an array of regular 32 bit ints. Its almost like it's chopping off the 8 bits of the wrong end of the int.

char strMAC = "11:22:33:AA:BB:CC";

typedef unsigned char UINT8;
UINT8 uMAC[6];

int iMAC[6];

sscanf( (const char*) strMac, 
        "%x:%x:%x:%x:%x:%x", 
        &uMAC[0], &uMAC[1], &uMAC[2], &uMAC[3], &uMAC[4], &uMAC[5] );
printf( "%x:%x:%x:%x:%x:%x", 
        uMAC[0], uMAC[1], uMAC[2], uMAC[3], uMAC[4], uMAC[5] );
// output: 0:0:0:0:0:0

sscanf( (const char*) strMac, 
        "%x:%x:%x:%x:%x:%x", 
        &iMAC[0], &iMAC[1], &iMAC[2], &iMAC[3], &iMAC[4], &iMAC[5] );
printf( "%x:%x:%x:%x:%x:%x", 
        iMAC[0], iMAC[1], iMAC[2], iMAC[3], iMAC[4], iMAC[5] );
// output: 11:22:33:AA:BB:CC



via Chebli Mohamed

Want to grab text from anywhere on my phone screen

I want to code this in java for Android use. The desired outcome is that I could grab a text from my phone screen from anywhere in any other app that displays text on the phone screen. How would I go about coding this app?



via Chebli Mohamed

Plot lat and lon from C code

I'm wondering, is there any way to plot map coordinates directly from C code? I'm getting a lat and lon from a TCP Stream I dissect using Wireshark and I want to create a dynamic map representation of the various points. Is there any API or system I can use to display these coordinates?

One situation I have is that the system has to run on a offline PC, so I would need to cache de various map data.

Is there any possible way of implementing this?

Thank you.



via Chebli Mohamed

What alterations must I do to this code.. I am receiving a Wrong answer message

All submissions for this problem are available.

Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction if X is a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction (including bank charges). For each successful withdrawal the bank charges 0.50 $US. Calculate Pooja's account balance after an attempted transaction. Input

Positive integer 0 < X <= 2000 - the amount of cash which Pooja wishes to withdraw. Nonnegative number 0<= Y <= 2000 with two digits of precision - Pooja's initial account balance. Output

Output the account balance after the attempted transaction, given as a number with two digits of precision. If there is not enough money in the account to complete the transaction, output the current bank balance.

  • Example - Successful Transaction

Input: 30 120.00

Output: 89.50

  • Example - Incorrect Withdrawal Amount (not multiple of 5)

Input: 42 120.00

Output: 120.00

  • Example - Insufficient Funds

Input: 300 120.00

Output: 120.00

**

  • In reference to the above problem... I am receiving a wrong output message on submission! Can somebody help me out? I believe i have covered all cases! But guys, do take a look

**

#include<stdio.h>
#define bank_charge 0.5
int main()
{
    float X, Y,new_balance;
    X=0, Y = 0;

    printf("With amt and balance ");
    scanf("%f%f", &X, &Y);
    if (X > 0 && X <= 2000 && Y >= 0 && Y <= 2000)
    {
        if (X > Y || ((Y-0.5-X)<0))
        {   printf("Insufficient Funds\n");
            printf("%0.2f", Y);
            return 0;

        }
        if ((int)X % 5 == 0)
        {
            new_balance = (Y - X) - bank_charge;
            printf("%0.2f", new_balance);
            return 0;

        }
        printf("%0.2f", Y);
            }
    return 0;
}



via Chebli Mohamed

how to delete an if statement without any code

I've constructed a Heap by using this code. However, there is one if statement without any codes so I'm trying to avoid using the if statement by giving it to the while statement.

Since the while statement is the opposite with the if. For instance, if(i==1) TRUE while(i!=1) TRUE

I've made the if statement opposite

if((*h).data[temp]<(*h).data[temp*2]&&(*h).data[temp]<(*h).data[temp*2+1])

while((*h).data[temp]>(*h).data[temp*2]&&(*h).data[temp]>(*h).data[temp*2+1])

and the result becomes different.

Here is my real source

int pop(heap* h)
{
int temp=1;
int min=(*h).data[1];
(*h).index--;
//head에 있는 것을 index의 것과 교환
(*h).data[1]=(*h).data[(*h).index];
(*h).data[(*h).index]=NULL;

//root가 가장 작은 경우
while(temp<(*h).capacity)
{
    if((*h).data[temp*2]!=NULL&&(*h).data[temp*2+1]!=NULL)
    {
        if((*h).data[temp]<(*h).data[temp*2]&&(*h).data[temp]<(*h).data[temp*2+1])
        {
        }
        else if((*h).data[temp*2]<(*h).data[temp*2+1])
        {
            //작은 것을 root와 교환
            (*h).data[temp*2]^=(*h).data[temp];
            (*h).data[temp]^=(*h).data[temp*2];
            (*h).data[temp*2]^=(*h).data[temp];
        }
        else if((*h).data[temp*2]>(*h).data[temp*2+1])
        {
            //작을 것을 root와 교환
            (*h).data[temp*2+1]^=(*h).data[temp];
            (*h).data[temp]^=(*h).data[temp*2+1];
            (*h).data[temp*2+1]^=(*h).data[temp];
        }
    }
    else if((*h).data[temp*2]!=NULL)
    {
        if((*h).data[temp*2]<(*h).data[temp])
        {
            (*h).data[temp*2]^=(*h).data[temp];
            (*h).data[temp]^=(*h).data[temp*2];
            (*h).data[temp*2]^=(*h).data[temp];
        }
    }
    temp*=2;
}

return min;

}



via Chebli Mohamed

Output of ++*p++

Can anyone explain me the output.

#include<stdio.h>
int main() {
    int a[]={10,20,30};
    int *p=a;
    ++*p++;
    printf("%d  %d  %d  %d",*p,a[0],a[1],a[2]);
}

output is 20 11 20 30

Postfix incrementation has a higher precedence, so value of second index should have been incremented. Why is the value of first index incremented?



via Chebli Mohamed

How to reduce a random hash to a boolean value

In c or a c-like language assuming I have a random_hash what is the cheapest way to reduce it to a boolean value i.e. 0 or 1?

An example random_hash to normalise answers: 0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa

Restrictions: no method/stdlib calls.

Why c-like, I'm actually trying to do it in a language called Solidity, which is modeled after c/javascript, which has a very limited runtime/stdlib.



via Chebli Mohamed

How to increase the potential value of an variable in a 16 bit machine using C

I have created a binary to decimal converter but even small numbers written in binary have many digits and thus are too large to be held by an integer variable on a 16 bit machine. Is there any way around this. The program is in C. Here is the code, thanks:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

void main()
{
 clrscr();
 int a,b,d=0,x=1;
 int check(int y);
 printf("Enter your number in Binary:");
 scanf("%d",&a);
 if(check(a)==0)
 {
  printf("Number tolerable. Conversion Process Initiated.");
 }
 else 
 {
  printf("Number not binary. Try again.");
  exit(1);
 }

 while(a!=0)
 {
   if(a%10==1)
    {
     d=d+x;
    }
   a=a/10;
   x=x*2;
 }
 printf("\nDecimal:%d",d);
 getch();
}

int check(int y)
{
  while(y!=0)
  {
   if(y%10!=0&&y%10!=1)
   {
    return 1;
   }
   else
   {
    y=y/10;
   }
  }
 return 0;
}



via Chebli Mohamed

C unknown syntax for variable declaration [duplicate]

This question already has an answer here:

I have just come across a piece of code that looks pretty much like this:

int a = ({

    int b = 10;
    b;
});

printf("%d", a);

I've never seen anything like this. It turns out that we can declare a variable this way. But why the language allows this? What is the concept behind it? When it can be of a good use to use such a syntax?



via Chebli Mohamed

Memory sharing between Matlab and C++ in MEX

I'm currently trying to write a program that processes a fairly large file (~16GB) and then performs analysis upon it. Ideally, I would do the data processing in C/C++ (I already have an efficient implementation written) and then do the analysis in Matlab to make use of its efficient algorithms and ease of use.

My natural inclination is to use MEX to call routines written in C at the beginning of the program and then continue in Matlab. What I want to know (and what I for whatever reason can't seem to find online) is the way in which memory would be shared if I were to use this method:

Say that I were to make a single large heap-allocated array in C to pass to Matlab. Would this array need to be copied in memory before my Matlab functions could work on it, or would Matlab be able to access the original array directly, with no extra copying? I assume and hope that this will work in the second way, but I would rather make sure before spending my time and effort.



via Chebli Mohamed

Using a pointer to access typedef struct

Objective: Writing to an internal buffer from the values of members of a structure.

I have a structure that contains members of type Uint16 (unsigned int); here is a small portion of it:

typedef unsigned int    Uint16;
typedef struct 
{
    Uint16 ee_Speed_Control_Mode;
    Uint16 ee_Motor_Type;
    Uint16 ee_Max_Electrical_Speed;
    Uint16 ee_Carrier_Frequency;
    Uint16 ee_Rated_Motor_Frequency;
    Uint16 ee_Rated_Motor_Current;
    Uint16 ee_Rs; // extern
    Uint16 ee_Rr; // extern
    Uint16 ee_L_lkg; // extern
    Uint16 ee_Lm;    // extern
    Uint16 ee_No_Load_Current;
    Uint16 ee_Phase_Reversal;
    .....
    .....
} EEPROM_PARAMETERS;

EEPROM_PARAMETERS eepromParameters;

My attempt:

Here is a function that is intended to write to eeprom: (Most of it is not shown for simplicity; the focus is occurring in the 'for' loop

void eeprom_write(Uint16 address, Uint32 *data, Int16 len)
{
    Uint16 i;

    // Multiple bytes will be written
    // Page Write operation will be used
    // Page Write bits to be sent:

    // bit 0: Start condition, a high-to-low transition of SDA with SCL high
    startCondition();

    // bits 1-8: Device address
    I2caRegs.I2CDXR = DEVICE_ADDRESS_WRITE;

    // bit 9: EEPROM outputs 0 as ACK bit
    // Check for ACK bit
    while (I2caRegs.I2CDRR != 0)
    {
        wait();
    }

    // bits 10-17, bit 18 (ACK) and bits 19-26: two 8-bit word addresses
    I2caRegs.I2CDXR = address;

    // After setting the address, page write is capable of writing 64 bytes without stopping
    // The EEPROM will respond with a zero after each data word has been received
    // The data word address lower 6 bits are internally incremented following the receipt of each data word
    // If more than 64 data words are written, data word addresses will "roll over" and previous data will be overwritten

    for (i = 0; i < len; i++)
    {
        // How to increment address in data structure?
        I2caRegs.I2CDXR = *data++; 
    }

    // After page write operation is complete, execute stop condition
    stopCondition();
}

When I try to call this function with my parameters..

eeprom_write(0, &eepromParameters, sizeof(eepromParameters) );

I get a incompatible type error:

error #169: argument of type "EEPROM_PARAMETERS *" is incompatible with parameter of type "Uint16 *"

My next thought would be that I need a middle man to bring them together and make it a compatible match. Any tips please on what I can try? Thanks



via Chebli Mohamed

Why does the image extracted from the Project Tango Tablet appear gray?

  • I am using the Project Tango C API
  • I am writing the entire buffer pointed to by TangoImageBuffer.data to a file.

    // open a file
    std::fstream f(app.getNextFileName(), std::ios::out | std::ios::binary);
    
    // write the entire stride * height * 4 buffer into the file
    f.write((const char *) tango_image_buffer->data, 
        tango_image_buffer->stride * buffer->height * 4 * sizeof(uint8_t)
    );
    
    f.close();
    
    
  • I then export the file to my PC and visualize it using python-opencv and numpy:

    import sys
    
    import cv2
    import numpy as np
    
    # dimensions of the image
    stride    = 1280
    width     = 1280
    height    = 720
    
    # I am using 3 channels so that the resulting image is not
    # transluscent
    channels  = 3
    
    input_filename  = sys.argv[1]
    output_filename = sys.argv[2]
    
    # load the image buffer into a list
    data = np.fromfile(input_filename, dtype=np.uint8)
    
    # create a height x width x channels matrix with the datatype uint8 
    # and all elements set to zero
    img = np.zeros((height, width, channels), dtype=np.uint8);
    
    # map elements in array to image matrix
    for y in range(0, height):    
        for x in range(0, width):
            img[y, x, 0] = data[y * stride + x + 2] #blue
            img[y, x, 1] = data[y * stride + x + 1] #green
            img[y, x, 2] = data[y * stride + x + 0] #red
    
    # display and save the resulting image
    cv2.namedWindow("tango-rgba")
    cv2.imshow("tango-rgba", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    cv2.imwrite(output_filename, img)
    
    
  • Unfortunately, the resulting image looks gray

  • The image only appears to be gray. Upon closer inspection of the pixels, you will find that the red, green, and blue components of the pixels are different.

  • EDIT: I have changed this post to specify that the buffer I am using is in RGBA8888 format. From the Project Tango Reference, "Only RGBA 8888 is provided"

  • EDIT: It actually seems RGBA8888 format is not used. rhashimoto suggests that the format is YV12.



via Chebli Mohamed

Strange segmentation fault in x86 assembly

While I'm debugging a segmentation fault in x86-Linux, I've ran into this problem:

Here goes the seg-fault message from the GDB

0xe2a5a99f in my_function (pSt=pSt@entry=0xe1d09000, version=43)

Here goes the faulting assembly:

0xe2a5a994 <my_function>      push   %ebp
0xe2a5a995 <my_function+1>    push   %edi
0xe2a5a996 <my_function+2>    push   %esi
0xe2a5a997 <my_function+3>    push   %ebx
0xe2a5a998 <my_function+4>    lea    -0x100b0c(%esp),%esp
0xe2a5a99f <my_function+11>   call   0xe29966cb <__x86.get_pc_thunk.bx>
0xe2a5a9a4 <my_function+16>   add    $0x9542c,%ebx

As you can see above, the faulting line is "call get_pc_thunk" which is just getting the pc value. And, I checked the memory at 0xe29966cb is valid and accessible with the following command:

(gdb) x/10i 0xe29966cb
   0xe29966cb <__x86.get_pc_thunk.bx>:  nop
   0xe29966cc <__x86.get_pc_thunk.bx+1>:        nop
   0xe29966cd <__x86.get_pc_thunk.bx+2>:        nop
   0xe29966ce <__x86.get_pc_thunk.bx+3>:        nop
   0xe29966cf <__x86.get_pc_thunk.bx+4>:        nop
   0xe29966d0 <__x86.get_pc_thunk.bx+5>:        nop
   0xe29966d1 <__x86.get_pc_thunk.bx+6>:        nop
   0xe29966d2 <__x86.get_pc_thunk.bx+7>:        nop
   0xe29966d3 <__x86.get_pc_thunk.bx+8>:        mov    (%esp),%ebx
   0xe29966d6 <__x86.get_pc_thunk.bx+11>:       ret    

Which looks perfectly fine. But Strangely, if I use "si" to step into the "get_pc_thunk" function, it seg-faults without even entering the first nop.

Any help would be appreciated.



via Chebli Mohamed

wrong answer on test case 1 in this code?

http://ift.tt/1SIFHF8

i tried to solve it. But my code all time results in wrong answer on test case 1. I don't understand the problem in this code.

#include <stdio.h>
int main ()
{ int n;
char a[10];
int s=0;
scanf ("%d",&n);

fflush(stdin);
for (int i=1;i<=n;i++)
{ gets(a);


    if (a[0]=='+' || a[1]=='+') s++;

   else  if (a[0]=='-' || a[1]=='-') s--;

}
printf ("%d\n",s);
return 0;
}



via Chebli Mohamed

Out of order print statements when using fortran program to call c subroutine

I am experiencing problems with displaying values on the console while invoking a C subroutine from a fortran subroutine. I have print statements immediately before and after the call to the C subroutine, as well as a print statement within the C subroutine. However, upon executing the program, the C statements are printed before the two Fortran statements, rather than between them. I’ve looked thoroughly within the code, and there are no calls to the C subroutine elsewhere, so there is no obvious reason why the c statement should be printed before the Fortran statement. I created a simpler Fortran-C program (below) to try to reproduce the problem, but the code executed the print statements in the expected order. I wonder if someone has any insights as to what could be the problem. Thank you.

Sample Fortran code:

  program test

     print *, 'Calling C program'

     call cprog()

     print *, 'Finished calling C program.'

   end program test

sample c code to be invoked from fortran:

void cprog()
{

  printf("THIS IS A TEST\n");

  return;
}

Output:

Calling C program

THIS IS A TEST

Finished calling C program.

Output similar to what I’m experiencing with more complex code:

THIS IS A TEST

Calling C program

Finished calling C program



via Chebli Mohamed

Array size calculation without using inbuilt functions

How to find the size of an integer array without using any inbuilt function?

int fun(int a[25],int ele)
{

    int flag=0,i=0;
    while(a[i]!=NULL)
    {
        flag++;
        i++;
    }
    return flag;
 }



via Chebli Mohamed

calculate lowesr differents between 5 cells to other 5 cells

I have this row - [11,19,59,69,9] lets call it FIRST and i have another ~ 100 million rows with the same format

[10,20,30,20,50],
[15,50,60,70,10]
...
...

I need to compare each number from FIRST row to each number in the corresponding cell in each row from the 100M rows , and take the abs diff between those two values and sum all of the diff.

Example :

FIRST - [11,19,59,69,9]
row   - [10,20,30,20,50]
diff  - [|11-10|,|19-20|,|59-30|,|69-20|,|9-50|]  = [1,1,29,49,41] 
sum(diff) = 1+1+29+49+41 =121

And i need to do this comparison between the FIRST and the rest of the rows and output the row with the smallest diff.

What is the best way to do it ? I need to implement it on my SQL DATABASE . Maybe there is SQL query for this ? or maybe i should develop some inner function via c, or c++?



via Chebli Mohamed

why the first index of the column of a matrix is negative?

why in this simple part of code to modify the point in the lower left of the bidimensional array have I to put in the coordinate m[37][-40]?

#include <stdio.h>
#include <stdlib.h>
#define MAX 40

int main()
{
    int i, j;
    char m[MAX][MAX];

    for(i=0; i<MAX; i++){
        for(j=0; j<MAX; j++)
            m[i][j]=' ';
    }

    m[37][-40]='X';

    for(i=0; i<MAX; i++){
        for(j=0; j<MAX; j++)
            printf("%c", m[i][j]);
    }
    return 0;
}

Souldn't it be m[37][0]? Becouse the row is 37 and the column is 0...



via Chebli Mohamed

Xlib get mouse wheel rate

Is there a property in X11 that tells how many scroll lines should there be in one scroll wheel event?



via Chebli Mohamed

Is there a difference in speed between using const and static const inside a function?

In C, what is the difference between static const and const inside a function?

For instance, take the given code examples:

void print_int(int x) {
  assert( x < 5 && x > -5 );
  const int i[9] = {
    -4, -3, -2, -1, 0, 1, 2, 3, 4
  };
  printf("%i", i[x + 4]);
}
int main() {
  print_int( 1 );
  return 0;
}

Versus:

void print_int(int x) {
  assert( x < 5 && x > -5 );
  static const int i[9] = {
    -4, -3, -2, -1, 0, 1, 2, 3, 4
  };
  printf("%i", i[x + 4]);
}
int main() {
  print_int(1);
  return 0;
}

Would the generated assembly be optimized better if I used static const instead of const, or would the output be the same for both examples?



via Chebli Mohamed

Eclipse error when trying to run C code

I'm trying to understand binary and hexadecimal numbers. I want to know why my program won't launch in eclipse. It gives me this error:

launch has encountered a problem

It was running when i used int. My computer is 64bit. I'm trying to understand hardware. I need to know what I'm doing wrong. What can I improve on? Is it okay to declare buffer as a global variable? Thanks.

My code is here.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * convertBase(unsigned long int numberToConvert, long int base)
{

    char buffer[65];
    char *pConvertedNumber;
    char allValues[] = "0123456789abcdef";

    pConvertedNumber = &buffer[sizeof(buffer)-1];

    *pConvertedNumber = '\0';

    do {

        int value = numberToConvert % base;

        pConvertedNumber = pConvertedNumber - 1;

        *pConvertedNumber = allValues[value];

        numberToConvert /= base;

    } while(numberToConvert != 0);

    printf("%s", pConvertedNumber);

    return pConvertedNumber;
}

int main(void){

    unsigned long int numberOne = 1000000000;
    printf("\n%ld in Base 16 = ", numberOne);
    convertBase(numberOne, 16);

    printf("\n");

return 0;
}



via Chebli Mohamed

Headers Vs. Static Libraries

I am planning to do some utility code for using in other projects, but I am doubting between making it a mostly-headers code, a static library with headers just exposing the interface or something in between. Most of the code will be simple functions that wrap other standard functions but there will be also some bigger functions.

I think I mostly understand the differences between the header approach and the static library approach:

For the headers:

  • All the code will be in headers
  • Better oportunities for the compiler to inline code
  • Every function will have to be compiled every time it is used

For the static library:

  • Mixed code between the library and the headers
  • Worse oportunities for the compiler to inline code
  • Compile once and forget

I have been looking at some code and I have seen both approaches, but I don't know which will be better. Any thoughts?



via Chebli Mohamed

How to control multiple robots through raspberry pi using bluetooth

I am trying to control two arduino robots through raspberry pi using Bluetooth, I have already created the rfcomm file to control one robot, should i include the address of the second one in same rfcomm file? if yes, could someone please tell me how?I've done this is it correct?please ignore the 'enter code here' part everywhere

RFCOMM configuration file.

enter code hererfcomm0 { enter code here # Automatically bind the device at startup enter code here bind yes;

   `enter code here` # Bluetooth address of the device
    `enter code here`device 30:14:10:15:20:90;


   `enter code here` # RFCOMM channel for the connection
   `enter code here` channel 0;


    `enter code here`# Description of the connection
    `enter code here`comment "Example Bluetooth device";

enter code here}

enter code hererfcomm1 { enter code here# Automatically bind the device at startup enter code herebind yes;

   `enter code here`# Bluetooth address of the device

   `enter code here` device 10:14:06:16:00:09;

  `enter code here` # RFCOMM channel for the connection
  `enter code here`  channel 0;

`enter code here` # Description of the connection
`enter code here`    comment "Example Bluetooth device";

enter code here}`



via Chebli Mohamed

Is there any limit to the number of expressions|parameters in a 'while loop' [duplicate]

This question already has an answer here:

Traditional programming with while-loop is done with a single parameter ex:

  • while(1) (or) while(a==b) (or) while(a&&b) (or) while(!a) etc
  • The code below takes two parameters in the while loop

    ssize_t r_read(int fd, void *buf, size_t size) 
    {
        ssize_t retval;
        while (retval = read(fd, buf, size), retval == -1 && errno == EINTR);
        return retval;
    }
    
    
    1. Is there any limit to the parameters inside the while loop?
    2. Is there any possible explanation for this or does this methodology have a name?


via Chebli Mohamed

8 Bit (Binary) array checking in c (embedded c)

I have an array a[j] . In it has an 8 bit binary digit . I need to check each bit whether it was zero or one . How to write the program in C .



via Chebli Mohamed

How to store 3 different types of data in one array

I need to store 3 linked bits of data in c. My original thought was a 3 dimensional array but that won't work as all 3 data types are different. The top level needs to be a char. The second level needs to be a date/time so a integer. The third level is a temperature reading so needs to be a float.

Is the correct way to do this an array of pointers pointing to an array of pointers pointing to a array of floats? If so how would that be written in C?



via Chebli Mohamed

Modify if-counter inside a loop

I'm trying to modify a counter in if loop because one array index number needs to be corresponded by the other in order for me to change the place of it's text, but the space between the strings add 1 to the counter.

for(int i = 0, n = strlen(p); i < n; i++){

    if(isspace(p[i])){
        c1 = x[i-1];
        printf("%c", p[i]);
    }
    if(isalpha(p[i])){
        c1 = x[i];
        c2 = c1-96;
        printf("%c --- %c ---%d\n",p[i],c1, c2);
    }

This is one of the attempts but it made an infinite loop, I've tried different approach like:

    if(isspace(p[i))){
        printf("%c", p[i]);
        i -= 1;
    }



via Chebli Mohamed

Why does my program display the Array address instead of its contents?

My C program consists of an array called 'test_var'. It has another integer array 'arr_int' that consists of a set of integer numbers. My code looks something like this:

 #include <stdlib.h>
 #include <stddef.h>
 #include <stdio.h>

 int State(var);
 int main()
       {
         int arr_int[3] ={1000, 1001, 1002, 1003};
         int var;
         int *test_var[4]={0};

         State(var)
         {
            int i;
            for(i=0; i<4; i++){
               test_var[i] = arr_int[i];
               i++;
                }
          return test_var[var];
          }

          printf("Enter a number between 0 and 3\n");
          scanf("%d",&var);   
          State(var);
          printf ("The array structure is %d", test_var[var]);

          return 0;
          }

However now when I try to print the returned value array test_var for the user input var=0 instead of the whole array(1000) I just get 0. What am I doing wrong here ? COuld somebody please tell me? Am I dereferencing the array in a wrong way?



via Chebli Mohamed

C: Zlib compress not working

I'm trying a very simple thing: read a minimal text file and compress it with the compress() utility from zlib. I think I've done everything fine, I allocate filesize * 10 for the output, it should be more that enough, but I keep getting -5 (Z_BUF_ERROR) as result of the operation. Any help?

#include <stdio.h>
#include <stdlib.h>
#include "zlib.h"

#define FILE_TO_OPEN "text.txt"

static char* readcontent(const char *filename, int* size)
{
    char* fcontent = NULL;
    int fsize = 0;
    FILE* fp = fopen(filename, "r");

    if(fp) {
        fseek(fp, 0, SEEK_END);
        fsize = ftell(fp);
        rewind(fp);

        fcontent = (char*) malloc(sizeof(char) * fsize);
        fread(fcontent, 1, fsize, fp);

        fclose(fp);
    }

    *size = fsize;
    return fcontent;
}

int main(int argc, char const *argv[])
{
    int input_size;
    char* content_of_file = readcontent(FILE_TO_OPEN, &input_size);

    printf("%d\n", input_size);

    uLongf compressed_data_size;
    char* compressed_data = malloc(sizeof(char) * (input_size * 10));

    int result = compress((Bytef*) compressed_data, (uLongf*)&compressed_data_size, (const Bytef*)content_of_file, (uLongf)input_size);
    printf("%d\n", result);

    return 0;
}



via Chebli Mohamed

Compiling on Mac

I am brand new to this forum, and have just begun to learn C. The book I am going through wants me to compile the code that was written. I have a file "cards.c", I am on a Mac, have Xcode installed, downloaded gcc from Apple and installed it.

$ gcc -v
Configured with: --prefix=/Applications/http://ift.tt/1d5DwEL --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.4.0
Thread model: posix

When I type:

gcc cards.c -o cards

I get:

clang: error: no such file or directory: 'cards.c'
clang: error: no input files

I have tried going to Xcode downloads to install Xcode's Command Line Tools, it doesn't show up there, maybe I have a newer version?

I cannot figure out how to compile this, any ideas on what I am doing wrong?

Does the cards.c file need to be in a specific folder somewhere?



via Chebli Mohamed

Efficient way to copying array of pointer to another pointer

How to copy array of pointer to another pointer.

My approach this way

int *ptr2[(i-1)*100];
int *ptr1;

ptr1=&ptr2[(i-1)*100];

What is the efficient way to copy so that it takes less cpu cycle.



via Chebli Mohamed

Expose c-library functionality to node

I have been working on using a c library in my node project. After little bit investigation I found node-gyp.

I was successfully able to execute example but when I am trying to using third party c library functions in the code it was giving me linking error on run time.

Library can be found here http://ift.tt/1SZL7q7

I compiled the library independently to have *.a objects

I am using following example http://ift.tt/1KO1IOs

So I have following questions as I can infer

  • Shall I convert bibutils from make to gyp?
  • Shall I convert each source file to work with V8? I don't know how to do this.
  • How can I easily link this project to work with node-gyp with less noise?

Details related to script can be found below. bibutils folder is placed along with addon.cc

binding.gyp looks like

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "addon.cc" ],
      "include_dirs": ["bibutils/lib"],
      "library_dirs": ["bibutils/lib/libbibutil.a","bibutils/lib/libbibprogs.a"]
    }
  ]
}

modified addon.cc

#include <node.h>
#include "bibutils.h"
#include "bibprogs.h"

using namespace v8;

void MyFunction(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
      /****This is not production code just to check the execution***/
      bibl b;   
      bibl_init( &b );
      bibl_free( &b );
      /**************************************************************/
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world"));
}

void CreateFunction(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);
  Local<Function> fn = tpl->GetFunction();

  // omit this to make it anonymous
  fn->SetName(String::NewFromUtf8(isolate, "theFunction"));

  args.GetReturnValue().Set(fn);
}

Compilation Result

user1@ubuntu:~/node-addon-examples/5_function_factory/node_0.12$ npm install

> function_factory@0.0.0 install /home/user1/node-addon-examples/5_function_factory/node_0.12
> node-gyp rebuild

make: Entering directory `/home/user1/node-addon-examples/5_function_factory/node_0.12/build'
  CXX(target) Release/obj.target/addon/addon.o
  SOLINK_MODULE(target) Release/obj.target/addon.node
  COPY Release/addon.node
make: Leaving directory `/home/user1/node-addon-examples/5_function_factory/node_0.12/build'

On Execution

user1@ubuntu:~/node-addon-examples/5_function_factory/node_0.12$ node addon.js
node: symbol lookup error: /home/user1/node-addon-examples/5_function_factory/node_0.12/build/Release/addon.node: undefined symbol: _Z9bibl_initP4bibl

Debug Info:

user1@ubuntu:~/node-addon-examples/5_function_factory/node_0.12$ nm -C build/Release/addon.node | grep bibl_init
                 U bibl_init(bibl*)



via Chebli Mohamed

Custom DNS answers

I'm currently working on a project for my summer internship and I've got to make an oblivious DNS translation server. I'm not here to speak about the oblivious part in detail but I'll explane the architecture of my program.

There is a server side that receives obfuscated requests and sends back an answer that it doesn't understand itself.

On the client side there is a proxy that translate requests into obfuscated requests. For that I use an iptables rule to send all DNS requests to a NFQUEUE, and then I work with libnetfilter_queue to handle the packet. After that I received the answer from the server I make a DNS answer with all the information I get (from the DNS request and from the server) and send it using libnet.

Now let's talk about my problem : When using my proxy I check the traffic with Wireshark and it seems that my proxy sends valid answers but if I try to browse the Internet with Firefox it doesn't work. You can find my code here : http://ift.tt/1SZL7pX

Is there a problem in my way of building DNS packets ?

Here is the DNS sender :

int send_answer(char *dst_ip_array, char *src_ip_array, int dport, int sport, int dns_id, char *query, char *req_ip, int logfd)
{
char c;
u_long src_ip = arrayToLong(src_ip_array), dst_ip = arrayToLong(dst_ip_array), requested_ip_long=dotToLong(req_ip);
char requested_ip[4];
u_short type = LIBNET_UDP_DNSV4_H;
libnet_t *l;

libnet_ptag_t ip;
libnet_ptag_t ptag4; /* TCP or UDP ptag */
libnet_ptag_t dns;

char errbuf[LIBNET_ERRBUF_SIZE];
char payload[1024];
u_short payload_s;
char log_buffer[500];
int length = 0;

/*
 *  Initialize the library.  Root priviledges are required.
 */
l = libnet_init(
        LIBNET_RAW4,                            /* injection type */
        NULL,                                   /* network interface */
        errbuf);                                /* error buffer */

if (!l)
{
    length += sprintf(log_buffer + length, "\tlibnet_init: %s", errbuf);
    exit(EXIT_FAILURE);
}

/* 
 * build dns payload 
 */
requested_ip[0]=requested_ip_long/(256*256*256);
requested_ip_long=requested_ip_long%(256*256*256);
requested_ip[1]=requested_ip_long/(256*256);
requested_ip_long=requested_ip_long%(256*256);
requested_ip[2]=requested_ip_long/256;
requested_ip_long=requested_ip_long%256;
requested_ip[3]=requested_ip_long;

payload_s = snprintf(payload, sizeof payload, "%c%s%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c", 
         (char)(strlen(query)&0xff), query, 0x00, 0x00, 0x01, 0x00, 0x01, 0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x0d, 0xe0, 0x00, 0x04, requested_ip[0], requested_ip[1], requested_ip[2], requested_ip[3]);

/* 
 * build packet
 */
dns = libnet_build_dnsv4(
type,          /* TCP or UDP */
dns_id,        /* id */
0x8100,        /* request */
1,             /* num_q */
1,             /* num_anws_rr */
0,             /* num_auth_rr */
0,             /* num_addi_rr */
payload,
payload_s,
l,
0
);

if (dns == -1)
{
    length += sprintf(log_buffer + length, "\tCan't build  DNS packet: %s\n", libnet_geterror(l));
    goto bad;
}

ptag4 = libnet_build_udp(
    sport,                                /* source port */
    dport,                                    /* destination port */
    LIBNET_UDP_H + LIBNET_UDP_DNSV4_H + payload_s, /* packet length */
    0,                                      /* checksum */
    NULL,                                   /* payload */
    0,                                      /* payload size */
    l,                                      /* libnet handle */
    0);                                     /* libnet id */

if (ptag4 == -1)
{
    length += sprintf(log_buffer + length, "\tCan't build UDP header: %s\n", libnet_geterror(l));
    goto bad;
}


ip = libnet_build_ipv4(
    LIBNET_IPV4_H + LIBNET_UDP_H + type + payload_s,/* length */
    0,                                          /* TOS */
    242,                                        /* IP ID */
    0,                                          /* IP Frag */
    64,                                         /* TTL */
    IPPROTO_UDP,                                /* protocol */
    0,                                          /* checksum */
    src_ip,                                     /* source IP */
    dst_ip,                                     /* destination IP */
    NULL,                                       /* payload */
    0,                                          /* payload size */
    l,                                          /* libnet handle */
    0);                                         /* libnet id */

if (ip == -1)
{
    length += sprintf(log_buffer + length, "\tCan't build IP header: %s\n", libnet_geterror(l));
    exit(EXIT_FAILURE);
}


/*
 * write to the wire
 */
c = libnet_write(l);
if (c == -1)
{
    length += sprintf(log_buffer + length, "\tWrite error: %s\n", libnet_geterror(l));
    goto bad;
}
else
{
    length += sprintf(log_buffer + length, "\tWrote %d byte DNS packet; check the wire.\n", c);
}
length = strlen(log_buffer);
write(logfd, log_buffer, length); // Write to the log.
libnet_destroy(l);
return (EXIT_SUCCESS);
bad:
length = strlen(log_buffer);
write(logfd, log_buffer, length); // Write to the log.
libnet_destroy(l);
return (EXIT_FAILURE);
}

Here is an example of DNS answer sent by my proxy: http://ift.tt/1KO1GGw



via Chebli Mohamed

Are there ready-to-use solutions (libraries, headers) or standard pattern/workflow for reading (a lot) input parameters? [on hold]

Heyho,

my situation

I have a quite big scientific c-program that needs a lot of input parameters reading out of a file. I have a "handmade" working version from the ones, working on the program before. But you have to keep a special order of the parameters, the formatted input file is kind of unhandy, adding of parameters is complicated and it is kind of error sensitive.

my ideas so far

If been looking for a while in different c introduction books and also in some advanced techniques guides, but nobody seems to write something about these kind of tasks.

The only thing, I could find, was the idea to use an external program that creates out of handy interface the sorted, unhandy to use directly input file I'm now using. But that takes more time and for adding/sorting/deleting parameters I have to change the program code and the input file generator.

my question

What kind of input handling strategy are there? Are there special coding techniques? Or a common workflow?

Please ask, if I have to specify things. I'm not use to common names and notations, sorry for that. Please correct me referring to this.



via Chebli Mohamed

Handling Decimals on Embedded C

I have my code below and I want to ask what's the best way in solving numbers (division, multiplication, logarithm, exponents) up to 4 decimals places? I'm using PIC16F1789 as my device.

float sensorValue;
float sensorAverage;

void main(){
    //Get an average data by testing 100 times
    for(int x = 0; x < 100; x++){
        // Get the total sum of all 100 data
        sensorValue = (sensorValue + ADC_GetConversion(SENSOR));
    }

    // Get the average
    sensorAverage = sensorValue/100.0;
}



via Chebli Mohamed

How to parse HEX Numbers in Bison

I have this project i'm suppose to work on and my first task is to build a deskCalculator. I want the calculator to be able to parse HEX numbers. Below is the section having the problem.

| HEX {$$ = strtol((char *)$1 , (char **)'\n', 16); }

A token HEX have been defined above and in the lex file the regular expresion have been defined as

hex [a-f0-9]+

The problem is at the level of the strtol function. Please Help me. Thanks.



via Chebli Mohamed

How to get disk name programmatically in Linux(Like "/dev/sda" or "/dev/sdb")?

I am trying out to find information related to Disk and partitions. Following are my code. But problem is that, I am passing disk name through command line by querying disk name from "/proc/partitions". Is there any api which can give me disk name as well.

#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <blkid/blkid.h>

int main (int argc, char *argv[])
{
 blkid_probe pr;
 blkid_partlist ls;
 int nparts, i;

 pr = blkid_new_probe_from_filename(argv[1]);
 if (!pr)
 err(2, "faild to open device %s", argv[1]);

 ls = blkid_probe_get_partitions(pr);
 nparts = blkid_partlist_numof_partitions(ls);

for (i = 0; i < nparts; i++)
{
blkid_partition par = blkid_partlist_get_partition(ls, i);
printf("PartNo = %d\npart_start = %llu\npart_size =  %llu\npart_type = 0x%x\n",
blkid_partition_get_partno(par),
blkid_partition_get_start(par),
blkid_partition_get_size(par),
blkid_partition_get_type(par));
}

blkid_free_probe(pr);
return 0;

}



via Chebli Mohamed

C file handling

I am just creating a basic file handling program. the code is this:

#include <stdio.h>
int main()
{
FILE *p;
p=fopen("D:\\TENLINES.TXT","r");
if(p==0)
{
    printf("Error",);

}

fclose(p);
}

This is giving Error, I cannot create files tried reinstalling the compiler and using different locations and names for files but no success. I am using Windows 7 and compiler is Dev C++ version 5



via Chebli Mohamed

Calling C from C#

I am from electric engineer background, therefore my knownledge is small about C#,DLL,etc.... I want to use c function into a C#. I know there is a couple post about that but I didn't find one that is enough simple.

Currently, I got C function call windows API to read/write on the USB port. First to create a .dll do I need a header file? Because I got the following function decleration function into a header. The examples that I saw on stack overflow and Internet only use a simple .c file, Can I get rid of the header files?

__declspec(dllexport) LMUSB_HANDLE  __stdcall InitializeDevice(unsigned short usVID,
                                    unsigned short usPID,
                                    LPGUID lpGUID,
                                    BOOL *pbDriverInstalled);
__declspec(dllexport) LMUSB_HANDLE  __stdcall InitializeDeviceByIndex(unsigned short usVID,
                                           unsigned short usPID,
                                           LPGUID lpGUID,
                                           DWORD dwIndex,
                                           BOOL bOpenDataEndpoints,
                                           BOOL *pbDriverInstalled);
__declspec(dllexport) BOOL  __stdcall TerminateDevice(LMUSB_HANDLE hHandle);
__declspec(dllexport) BOOL  __stdcall WriteUSBPacket(LMUSB_HANDLE hHandle,
                          unsigned char *pcBuffer,
                          unsigned long ulSize,
                          unsigned long *pulWritten);
__declspec(dllexport) DWORD  __stdcall ReadUSBPacket(LMUSB_HANDLE hHandle,
                         unsigned char *pcBuffer,
                         unsigned long ulSize,
                         unsigned long *pulRead,
                         unsigned long ulTimeoutMs,
                         HANDLE hBreak);
 __declspec(dllexport) BOOL  __stdcall Endpoint0Transfer(LMUSB_HANDLE hHandle, UCHAR ucRequestType,
                             UCHAR ucRequest, USHORT usValue,
                             USHORT usIndex, USHORT usLength,
                             PUCHAR pucBuffer, PUSHORT pusCount);

Second point, do I need to write __declspec(dllexport) in the cpp file? Here an function from the cpp:

extern "C" __declspec(dllexport) BOOL PASCAL EXPORT TerminateDevice(LMUSB_HANDLE hUSB)

I got no idea what "BOOL PASCAL EXPORT" does, this code is recycled from a furnisher project.

Finaly, when the DLL is properly build. How I import it in the C# project? I tried the following but without success :

[DllImport("lmusbdll.dll")]

I see that you could use right click on the project and add reference but Visual Studio pop-up an error message:

A reference to "DLL path" could not be added. Please make sure that the file is accessible, and that it is a valid assembly or COM component.

[EDIT]

I tried the following solution , but when I tried to reference the header file in my c# project. I still get the message that I cannot reference the file.



via Chebli Mohamed

Usage of keyword const in a function argument [duplicate]

This question already has an answer here:

Taking the following example:

void foo(const int foobar);

Is the keyword const meaningful?



via Chebli Mohamed

Difference between Internal terminal, External terminal and Standard output in Netbeans

I just got to know there are multiple consoles in Netbeans when working on a C-program. Please let me know what are the differences between them and when will they be used. Please see the screenshot

enter image description here



via Chebli Mohamed

Data compare of files is wrong. Why? [on hold]

So, the thing is, this program checks if there are duplicate files in a directory. It uses mostly the windows.h library. To spare code, all the file paths are stored in the buffer finalizedList. The list is always correct, don't worry about it.

To show you the problem, here are the files in the directory:

  • duplicate_delete.exe = The program itself
  • hello.txt = The original text file
  • hello - Copy.txt = A duplicate of "hello.txt". They are exactly the same.
  • hello.cpp = A file that has the exact same name with the original text file, except its extension. (AKA "The Bad Guy")

Now, anytime I run the program while "hello.cpp" is in the directory, this is the output of the program:

Creating list...
Finalizing list...
Starting compare procedure...
Checking: duplicate_delete.exe vs. hello - Copy.txt --> DIFFERENT
Checking: duplicate_delete.exe vs. hello.cpp --> DIFFERENT
Checking: duplicate_delete.exe vs. hello.txt --> DIFFERENT
Checking: hello - Copy.txt vs. hello.cpp --> DIFFERENT
Checking: hello - Copy.txt vs. hello.txt --> DIFFERENT
Checking: hello.cpp vs. hello.txt --> DIFFERENT
Finished.
Press any key to continue . . .

But, when I delete that file the output is this:

Creating list...
Finalizing list...
Starting compare procedure...
Checking: duplicate_delete.exe vs. hello - Copy.txt --> DIFFERENT
Checking: duplicate_delete.exe vs. hello.txt --> DIFFERENT
Checking: hello - Copy.txt vs. hello.txt --> DUPLICATE
Finished.
Press any key to continue . . .

Now... Why does that happen? Or to put it in a better way, how can that happen?

Here are parts of the code:

#include <windows.h>
#include <stdio.h>

HANDLE file1, file2;
const WCHAR * finalizedList[] = { L"duplicate_delete.exe", L"hello - Copy.txt", L"hello.txt", L"hello.cpp" };
WCHAR deleteList[4][1024];
DWORD fileListP, deleteListP;

DWORD openFile1(WCHAR path[1024]);
DWORD openFile2(WCHAR path[1024]);
DWORD compare();
void startCompare();

int main(void)
{
    fileListP = 4;
    printf_s("Starting compare procedure...\n");
    startCompare();
    printf_s("Finished.\n");
    _fcloseall();
    system("pause");

    return 0;
}

DWORD openFile1(WCHAR path[1024])
{
    if ((file1 = CreateFile(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) return 0;
    return 1;
}

DWORD openFile2(WCHAR path[1024])
{
    if ((file2 = CreateFile(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) return 0;
    return 1;
}

DWORD compare()
{
    DWORD a, b;
    BYTE byte1, byte2;

    while (1)
    {
        ReadFile(file1, &byte1, 1, &a, NULL);
        ReadFile(file2, &byte2, 1, &b, NULL);
        if (a != b) return 1;
        if (byte2 != byte1) return 1;
        if (a == 0 && b == 0) break;
    }

    return 0;
}

void startCompare()
{
    WCHAR currentFile[1024], comparedFile[1024];
    DWORD i, j;
    i = 0;

    for (j = 0; j < fileListP; ++j)
    {
        lstrcpy(currentFile, finalizedList[j]);
        if (!openFile1(currentFile)) wprintf(L"File \"%ls\" couldn not be opened for comparing.\n", currentFile);
        else
        {
            for (i = j + 1; i < fileListP; ++i)
            {
                lstrcpy(comparedFile, finalizedList[i]);
                if (!openFile2(comparedFile)) wprintf(L"File \"%ls\" couldn not be compared with file \"%ls\".\n", currentFile, comparedFile);
                else
                {
                    if (!compare())
                    {
                        wprintf(L"Checking: %ls vs. %ls --> DUPLICATE\n", currentFile, comparedFile);
                        lstrcpy(deleteList[deleteListP], currentFile);
                        ++deleteListP;
                    }
                    else
                    {
                        wprintf(L"Checking: %ls vs. %ls --> DIFFERENT\n", currentFile, comparedFile);
                    }
                    CloseHandle(file2);
                }
            }
            CloseHandle(file1);
        }
    }
}

Now... Of course, when I'm to check the program without the hello.cpp file I just delete it from the finalizedList array and make fileListP equal to 3. This is the minimal code that will work.



via Chebli Mohamed