smallseo.info

c# interview questions

Top c# frequently asked interview questions

Change I2C address Linux driver kernel

I have a system which uses module Sensors LM75 with two I2C adresses (0x48 and 0x49). I'd like to cancel one address (0x48), however I don't understand where there is its initialisation.

All changes in normal_i2c , are not relevant ....

/* Addresses scanned */
static const unsigned short normal_i2c[] = { 0x48, 0x49, 0x4a, 0x4b, 0x4c,
                    0x4d, 0x4e, 0x4f, I2C_CLIENT_END };

Source: (StackOverflow)

mongoLab C driver authentication and Basic Example

I am trying to interface Official C driver with mongoLab but getting error that failed to authenticate credentials. Do anyone have any simple example on how to interface mongolab using C driver. This is my example code

const char* String_uri = "mongodb://<username>:<pwd>@ds011115.mongolab.com:11115/tempdb";

    uri = mongoc_uri_new(String_uri);
    client = mongoc_client_new_from_uri (uri);


   collection = mongoc_client_get_collection (client, "mydb", "mycoll");
   doc = bson_new_from_json ((const uint8_t *)"{\"hello\" : \"world\"}", -1, &error);

   count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, doc, 0, 0, NULL, &error);

   if (count < 0) {
      fprintf (stderr, "%s\n", error.message);
   } else {
      printf ("%" PRId64 "\n", count);
   }

Source: (StackOverflow)

tm struct time.h not normalizing

I am adding values to the time (hours, minutes, seconds) members of my tm struct and they are not updating/normalizing even though I'm using mktime() Here is the code:

struct tm timeStruct;
char buffer[80];

timeStruct.tm_year = 2016 - 1900;
timeStruct.tm_mon = 3;
timeStruct.tm_mday = 32;
timeStruct.tm_hour = 23;
timeStruct.tm_min = 59;
timeStruct.tm_sec = 59;
timeStruct.tm_isdst = -1;

printf( "Date before adding interval: \n");
mktime(&timeStruct);
strftime(buffer, sizeof(buffer), "%c", &timeStruct);
printf(buffer);

printf( "\nthe year is %d\n", timeStruct.tm_year );
printf( "the month is %d\n", timeStruct.tm_mon );
printf( "the day is %d\n", timeStruct.tm_mday );
printf( "the hours are %d\n", timeStruct.tm_hour );
printf( "the minutes are %d\n", timeStruct.tm_min );
printf( "the seconds are %d\n", timeStruct.tm_sec );

/*
 * Add intervals to time
 */
timeStruct.tm_sec += 2;
timeStruct.tm_min += 2;
timeStruct.tm_hour += 5;

printf( "Date after adding interval: \n");
strftime(buffer, sizeof(buffer), "%c", &timeStruct);
printf(buffer);

printf( "\nthe year is %d\n", timeStruct.tm_year );
printf( "the month is %d\n", timeStruct.tm_mon );
printf( "the day is %d\n", timeStruct.tm_mday );
printf( "the hours are %d\n", timeStruct.tm_hour );
printf( "the minutes are %d\n", timeStruct.tm_min );
printf( "the seconds are %d\n", timeStruct.tm_sec );

Console Output:1

This is a print out of the console output:

Date before adding interval: 
Mon May  2 23:59:59 2016
the year is 116
the month is 4
the day is 2
the hours are 23
the minutes are 59
the seconds are 59
Date after adding interval: 
Mon May  2 28:61:61 2016
the year is 116
the month is 4
the day is 2
the hours are 28
the minutes are 61
the seconds are 61

I am using Eclipse, compiling with Cygwin, on a Windows 7 machine.


Source: (StackOverflow)

Having trouble using a C library via a Python API: What am I doing wrong?

I'm using a Python script in conjunction with a thermocouple and a thermocouple reader. To communicate with the thermocouple reader, which is written in C, I have to use an API. That API is PyDAQFlex. The thermocouple reader also came with a tester script, written in C. I'm trying to get a temperature reading from the thermocouple reader, but it only outputs the CJC value.

My code:

import daqflex

d = daqflex.USB_2001_TC()

def get_temperature():
    return float(d.send_message("?AI{0}:CJC/DEGC").encode("utf-8"))

The output of my code:

u'AI{0}:CJC/DEGC=23.8'

Note: 23.8 is not the temperature. That value is the CJC, as seen in the tester script's command line output below. It's related, but not the value I'm looking for.


The tester script's code:

http://pastebin.com/Atsdy7X0 (to get the temperature, I press "t" and then "k" because I have a K-type thermocouple).

The tester script's command line output:

http://pastebin.com/jq4Rr4QX (the temperature here is accurate. This is what I want to plug into my script.)


The PyDAQFlex script:

https://github.com/torfbolt/PyDAQFlex/blob/master/daqflex/devices.py (see line 105)

The C code for the thermocouple reader:

http://pastebin.com/rEDR9efR (Not included in entirety, only the relevant parts.)


I am seriously struggling to see my mistake here. This exact piece of code appears to have worked for someone else in the PyDAQFlex Github page, so I'm extremely confused. I have emailed the creator of the software, a person in Github with a similar issue as me, and I just spent 6 hours in various IRC chats. Please help me. If it helps, I used parts of this tutorial to install the drivers and things for the thermocouple reader. Thank you so much.


Source: (StackOverflow)

Read the entire contents of a file to c char *, including new lines

I'm looking for a cross platform (Windows + Linux) solution to reading the contents of an entire file into a char *.

This is what I've got now:

FILE *stream;
char *contents;
fileSize = 0;

//Open the stream
stream = fopen(argv[1], "r");

//Steak to the end of the file to determine the file size
fseek(stream, 0L, SEEK_END);
fileSize = ftell(stream);
fseek(stream, 0L, SEEK_SET);

//Allocate enough memory (should I add 1 for the \0?)
contents = (char *)malloc(fileSize);

//Read the file 
fscanf(stream, "%s", contents);     

//Print it again for debugging
printf("Read %s\n", contents);

Unfortunately this will only print the first line in the file so I assume that fscanf stops at the first newline character. However I would like to read the entire file including, and preserving, the new line characters. I'd prefer not to use a while loop and realloc to manually construct the entire string, I mean there has to be a simpler way?


Source: (StackOverflow)

Tree: Level order Traversal using queue

I wrote codes that traversing tree using queue, but dequeue function below generates error, Is there any problem with head = p->next ? I cannot figure out why this part is wrong.

void Levelorder(void) {
node *tmp, *p;


if (root == NULL) return;

tmp = root;
printf("The level order is :\n");

while (tmp != NULL) {

    printf("%d, ", tmp->data);
    if (tmp->left) {
        enqueue(tmp->left);
    }
    if (tmp->right) {
        enqueue(tmp->right);
    }
    tmp = dequeue();
}

return;
}

void enqueue(node *p) {
if (head == NULL) {
    head = p;
}
else {
    tail->next = p;
}
tail = p;
p->next = NULL;
tail->next = NULL;

return;
}

node* dequeue(void) {
node *p;
p = head;
head = p->next;


if (head == NULL) {
    tail == NULL;
}

return p;
}

Source: (StackOverflow)

program crash on sending data over a pipe to mplayer

I have a program I wrote in C that starts mplayer with a pipe, I then control mplayer through that pipe. It seems that at times when I send a command over the pipe it crashes. The following are the relevant parts of my code and what I have done to debug it.

The original code:

FILE *mplayer_pipe;
char temp[256];

bzero(temp,256);
sprintf(temp,"mplayer -quiet -slave video.mkv > mplayer.log");
mplayer_pipe = popen((char*)temp, "w");

/* watch some values to see what to do next */

/* if I see a value that means I should stop mplayer I do this */

fputs("stop\n",mplayer_pipe);
fflush(mplayer_pipe);
pclose(mplayer_pipe);

I ran into the problem that if mplayer finished, thus making it so nothing is at the other end of the pipe and I still pipe over the stop my program crashes. To solve this I changed it to the following:

FILE *mplayer_pipe;
char temp[256];

bzero(temp,256);
sprintf(temp,"mplayer -quiet -slave video.mkv > mplayer.log");
mplayer_pipe = popen((char*)temp, "w");

/* watch some values to see what to do next */

/* if I see a value that means I should stop mplayer I do this */

FILE *mplayer_status;
int mplayer_pid = 0;
char status_read_char[256];
bzero(status_read_char,256);

mplayer_status = popen("pidof -s mplayer", "r");
fgets(status_read_char, 6, mplayer_status);
pclose(status_read_char);
mplayer_pid = atoi(status_read_char);

if(mplayer_pid > 0) {
fputs("stop\n",mplayer_pipe);
fflush(mplayer_pipe);
pclose(mplayer_pipe);
}
else {
pclose(mplayer_pipe);
}

This fix worked great for me and it stop crashing.

Then I let other use the program and I starting getting crashing every once in a while. As I could not get my program to crash myself I change it to the following to see where the program was crashing.

FILE *mplayer_pipe;
char temp[256];

bzero(temp,256);
sprintf(temp,"mplayer -quiet -slave video.mkv > mplayer.log");
mplayer_pipe = popen((char*)temp, "w");
printf("command: mplayer -quiet -slave video.mkv > mplayer.log");

/* watch some values to see what to do next */

/* if I see a value that means I should stop mplayer I do this */

FILE *mplayer_status;
int mplayer_pid = 0;
char status_read_char[256];
bzero(status_read_char,256);

mplayer_status = popen("pidof -s mplayer", "r");
fgets(status_read_char, 6, mplayer_status);
pclose(status_read_char);
mplayer_pid = atoi(status_read_char);
printf("mplayer_status: command: pidof -s mplayer. Got %s, value %d.",status_read_char,mplayer_pid);

if(mplayer_pid > 0) {
fputs("stop\n",mplayer_pipe);
fflush(mplayer_pipe);
printf("command: stop.");
pclose(mplayer_pipe);
}
else {
pclose(mplayer_pipe);
}

The last thing I got before my program crashed the next time was:

mplayer_status: command: pidof -s mplayer. Got 27323, value 27323.

To me this indicates that it is crashing while piping over the stop command to mplayer.

Does anyone know what is going wrong here? And any ideas on how to prevent it from crashing?


Source: (StackOverflow)

How to create a linear list for storing 10,20,30 using linked list?

How can I implement a linked list for storing 10,20,30 .Please help me with a simple example.


Source: (StackOverflow)

C Sockets Client/Server pthreads server broadcast

We were given this code, and was supposed to modify it so that whenever a client connects to a server and sends a message the server should reply I hear you dude. That is working for one and multiple clients but next task was to when ever a new client connects the server should tell that to all the other clients that are connected.

I assumed this would be fairly easy but its not working out like I thought it would. Since the server always get sock 3 and first client gets 4 and second client gets 5 etc, I tried to make a for loop that messaged whenever a new client connects the loop will send message to 4,5 which just made the server close itself directly. I then tried to just make when ever a new client connects that the server should message the first client(4) which it actually does but only if client(4) writes a message to the server he recieves that broadcast that the server sent.

So it seems like the client wants to write but needs to write something before he recieves the broadcast from the server, any help would appreciated since we're kinda beginners with all this.

This is how the code looks like at the moment.

server.c

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/times.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <pthread.h>

#define PORT 5555
#define MAXMSG 512


void *connection_handler(void *socket_desc)
{
    int sock = *(int*)socket_desc;
    int read_size;
    char *message, client_message[2000], *message_to_client;
    message = "Greetings! I am your connection handler\n";
    write(sock, message, strlen(message));
    while( (read_size = recv(sock, client_message, 2000, 0)) > 0)
    {
       client_message[read_size] = '\0';
       printf("Client[%d]: %s", sock, client_message);
       message_to_client = "I hear you dude...";
       write(sock, message_to_client, 19);
       memset(client_message, 0, 2000);
    }

    if(read_size == 0)
    {
       printf("Client[%d] disconnected", sock);
       fflush(stdout);
    }
    else if(read_size == -1)
    {
       perror("recv failed");

    }
    free(socket_desc);
    return 0;
}

int makeSocket(unsigned short int port) {
    int sock;
    struct sockaddr_in name;
    /* Create a socket. */
    sock = socket(PF_INET, SOCK_STREAM, 0);
    if(sock < 0) {
        perror("Could not create a socket\n");
        exit(EXIT_FAILURE);
    }
    name.sin_family = AF_INET;
    name.sin_port = htons(port);
    name.sin_addr.s_addr = htonl(INADDR_ANY);
    if(bind(sock, (struct sockaddr *)&name, sizeof(name)) < 0) {
        perror("Could not bind a name to the socket\n");
        exit(EXIT_FAILURE);
    }
    return(sock);
}

int main(int argc, char *argv[])
{
    int sock;
    int clientSocket;
    int i;
    int *new_sock;
    char *broadcast;
    fd_set activeFdSet, readFdSet;
    struct sockaddr_in clientName;
    socklen_t size;
    sock = makeSocket(PORT);
    if(listen(sock,1) < 0) 
    {
        perror("Could not listen for connections\n");
        exit(EXIT_FAILURE);
    }
    FD_ZERO(&activeFdSet);
    FD_SET(sock, &activeFdSet);
    while(1) 
    {
        printf("Waiting for connections\n");
        readFdSet = activeFdSet;
        if(select(FD_SETSIZE, &readFdSet, NULL, NULL, NULL) < 0)
        {
            perror("Select failed\n");
            exit(EXIT_FAILURE);
        }
        for(i = 0; i < FD_SETSIZE; ++i)
        {
            if(FD_ISSET(i, &readFdSet)) 
            {
                if(i == sock) 
                {
                    size = sizeof(struct sockaddr_in);
                    pthread_t sniffer_thread;
                    while(( clientSocket = accept(sock, (struct sockaddr *)&clientName, (socklen_t *)&size))) 
                    {
                        puts("Connection accepted");
                        new_sock = malloc(1);
                        *new_sock = clientSocket;
                        if( pthread_create( &sniffer_thread, NULL, connection_handler, (void*) new_sock) < 0)
                        {
                            perror("could not create thread");
                            return 1;
                        }
                        broadcast = "NEW CLIENT CONNECTED";
                        write(4, broadcast, sizeof(broadcast)); //just to see if when ever a new client connects the first client should get all these messages
                        write(4, broadcast, sizeof(broadcast));
                        write(4, broadcast, sizeof(broadcast));
                        pthread_detach(sniffer_thread);
                        puts("Handler assigned");
                        FD_SET(*new_sock, &activeFdSet);

                   }
                   if(clientSocket < 0) 
                   {
                       perror("Could not accept connection\n");
                       exit(EXIT_FAILURE);
                   }                
                }
                else 
                {
                    if(readMessageFromClient(i) < 0)
                    {
                    close(i);
                        FD_CLR(i, &activeFdSet);
                    }
                }
            }
        }      
    }
} 

and for the client the code looks like this

client.c

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#define PORT 5555
#define hostNameLength 50
#define messageLength  256

void initSocketAddress(struct sockaddr_in *name, char *hostName, unsigned short int port) 
{
  struct hostent *hostInfo; 
  name->sin_family = AF_INET;
  name->sin_port = htons(port);
  hostInfo = gethostbyname(hostName);
  if(hostInfo == NULL)
  {
    fprintf(stderr, "initSocketAddress - Unknown host %s\n",hostName);
    exit(EXIT_FAILURE);
  }
  name->sin_addr = *(struct in_addr *)hostInfo->h_addr;
}
void writeMessage(int fileDescriptor, char *message) 
{
  int nOfBytes;
  nOfBytes = write(fileDescriptor, message, strlen(message) + 1);
  if(nOfBytes < 0) 
  {
    perror("writeMessage - Could not write data\n");
    exit(EXIT_FAILURE);
  }
}

int main(int argc, char *argv[]) 
{
  int sock;
  struct sockaddr_in serverName;
  char hostName[hostNameLength];
  char messageString[messageLength];
  char buffer[1024];
  if(argv[1] == NULL) 
  {
    perror("Usage: client [host name]\n");
    exit(EXIT_FAILURE);
  }
  else 
  {
    strncpy(hostName, argv[1], hostNameLength);
    hostName[hostNameLength - 1] = '\0';
  }

  sock = socket(PF_INET, SOCK_STREAM, 0);
  if(sock < 0) 
  {
    perror("Could not create a socket\n");
    exit(EXIT_FAILURE);
  }

  initSocketAddress(&serverName, hostName, PORT);
  if(connect(sock, (struct sockaddr *)&serverName, sizeof(serverName)) < 0) 
  {
    perror("Could not connect to server\n");
    exit(EXIT_FAILURE);
  }
  printf("\nType something and press [RETURN] to send it to the server.\n");
  printf("Type 'quit' to nuke this program.\n");
  fflush(stdin);
  recv(sock, buffer, 1024, 0);
  printf(buffer);
  while(1) 
  {
    printf("\n>");
      fgets(messageString, messageLength, stdin);
      messageString[messageLength - 1] = '\0';
      if(strncmp(messageString, "quit\n",messageLength) != 0)
         writeMessage(sock, messageString);
      if(recv(sock, buffer, 1024, 0) > 0)
               printf(buffer);


  }
}

Source: (StackOverflow)

Why does this simple program keep crashing visual studio 2013

This relatively simple program keeps on crashing my visual studio 2013, it doesn't give me an error message that i can tell you guys and from looking at my program I can't see any major flaws with it. Visual studio tries to debug it and than crashes. Can someone tell me what is wrong with my program?

#include <stdio.h>
int main()
{
    int a = 0, counter, total = 0;
    printf("enter the number of terms you want to display\n");
    scanf_s("%d", a);
    for (counter = 0; counter <= a; counter++){
        total = counter + total;
        printf("%d + ", total);
    }



    printf("You have finished the program, press enter to exit");       /*Letting the user know that the program is finished*/



}

Source: (StackOverflow)

How can I use getOpt to determine if no options are given in C?

I'm working on a simple program that supposed to change a string to all uppercase or all lowercase depending on the arguments. For example, if the programs name is change:

./change -u thiswillbeuppercase

THISWILLBEUPPERCASE

./change -l THISWILLBELOWERCASE

thiswillbelowercase

The issue im having if that i cannot figure out how to perform the uppercase action by default, if no options are provided. For example, this is how i would like it to perform:

./change thiswillbeuppercase

THISWILLBEUPPERCASE

Here is what my main function looks like currently:

int main(int argc, char *argv[]) {
int c;
while((c = getopt(argc,argv,"u:s:l:")) != -1){
    char *str = optarg;
    if(c == '?'){
        c = optopt;
        printf("Illegal option %c\n",c);
    } else{

        switch(c){
            case 'u':
                strupper(str);
                break;
            case 'l':
                strlower(str);
                break;
            case 's':
                strswitch(str);
                break;
            default:
                strupper(str);
                break;

        }
    }

}
return 0;

}

I tried calling the strupper function in the default part of the switch statement but that doesn't seem to work. As of now the program does nothing when provided with no options.

I search stackoverflow for similar questions and i found someone with the same issue, but their question is related to bash and not C.

If anyone has any advice i would really appreciate it. Thank you.


Source: (StackOverflow)

Count alphabets in C using log functions(without math.h) and arrays

I'm facing a slight problem with one of my projects. I am supposed to write a c program to calculate each character present in the input/file. (It's supposed to be a basic program.) The constraints - I cannot use the math.h library to produce log functions and obtain an output in the format:

    1                                           
    5   1 2 0 2 2 5 8     4 3 6 6 2   5 5 7 2 1 1   2   
    7 9 8 1 7 2 4 1 0 0 4 5 0 2 2 5 2 6 3 6 6 3 7 0 2 2 
    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

The program is supposed to count the number of occurrences of each alphabetic letter (case insensitive) in the stdin input stream and display a histogram.

As you can see, the output is formatted vertically with each line printing the base 10 number of the position of the character. Now, this might seem silly, but what I have so far is this:

    #include <stdio.h>
    #include <ctype.h>

    /*
    int logBase10 (int num) {
       method to calculate the log base 10 of num
    }
    */

    int main (int argc, char * argv[]) {
        char alpha;
        int count = 0;
        int ascii[128] = {0};

        while ( (alpha = getchar()) != EOF) {
            count++;
            ascii[(int)alpha]++;
            alpha = getchar();
        }

        printf("Char \t Count \n");
        printf("------------------------\n");

        for (int i = 0; i < 127; i++) {
            if(ascii[i] > 0) {
                printf("%c \t %d \n", i, ascii[i]);
            }
        }
    }

Which produces an output like this:

    Char     Count 
    ------------------------

         5 
         93 
    ,    6 
    -    2 
    .    3 
    ;    2 
    C    2 
    I    6 
    N    1 
    T    1 
    W    2 
    a    26 
    b    5 
    c    8 
    d    13 
    e    55 
    f    11 
    g    7 
    h    28 
    i    32 
    k    3 
    l    26 
    m    17 
    n    31 
    o    27 
    p    12 
    q    1 
    r    26 
    s    22 
    t    42 
    u    11 
    v    8 
    w    8 
    y    13 
    z    1 

First off, my program is printing unwanted ascii characters (, ; - etc) and I am working on changing the print function to be more vertical, but I cannot figure out the log method at all. I know log(10) is 1 because 10^1 is 1, but I am having trouble figuring out how to use this to create the method itself. Also, for the extra characters, I tried using:

    if(ascii[i] > 65 || ascii[i] < 90 || ascii[i] >= 97 || ascii[i] <= 122 ) {
        printf("%c \t %d \n", i, ascii[i]);
    }

to no avail. Trying that produced more gibberish characters instead.

Any help/feedback is appreciated.

  • Soul

Source: (StackOverflow)

Rotate words around vowels in C

I am trying to write a program that reads the stdin stream looking for words (consecutive alphabetic characters) and for each word rotates it left to the first vowel (e.g. "friend" rotates to "iendfr") and writes this sequence out in place of the original word. All other characters are written to stdout unchanged.

So far, I have managed to reverse the letters, but have been unable to do much more. Any suggestions?

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_STK_SIZE 256

char stk[MAX_STK_SIZE];
int tos = 0; // next available place to put char

void push(int c) {
    if (tos >= MAX_STK_SIZE) return;
    stk[tos++] = c;
}

void putStk() {
    while (tos >= 0) {
        putchar(stk[--tos]);
    }
}

int main (int charc, char * argv[]) {
    int c;
    do {
        c = getchar();
        if (isalpha(c) && (c == 'a' || c == 'A' || c == 'e' || c ==         'E' || c == 'i' || c == 'o' || c == 'O' || c == 'u' || c == 'U')) {
            push(c);
        } else if (isalpha(c)) {
            push(c);
        } else {
            putStk();
            putchar(c);
        }
    } while (c != EOF);
}

-Soul


Source: (StackOverflow)

Redirecting file contents into another program in C

Making a basic shell and I need to handle file redirection. Specifically I am stumped on how I can feed data into a program like sort for example from a file.

Something on the command line would look like this:

$ sort < test.txt

How do I accomplish this kind of functionality in my own mini shell made in C?

I thought that maybe sort read from stdin but I guess I can't really write the contents of a file to stdin due to the read only aspect so I'm wondering how I actually get this data into something like sort for example? I am currently using forks and then using execvp() to execute programs.


Source: (StackOverflow)

Failed to build a naive project using Visual Studio 2015

I have failed to build a naive project using Visual Studio 2015.

It's a matter of environment which is still not fixed.

I am using Windows 10 Education, using Visual Studio Enterprise 2015.

Thank you so much for your help.

Error   TRK0005 Failed to locate: "CL.exe". The system cannot find the file specified.  myproj  D:\Documents\XXX    1   

Source: (StackOverflow)