working on it ...

Filters

snippets
15k
followers
41
Published by snip2code

C

This channel collects useful snippets for C language
Sort by

Found 15k snippets

    public by snip2code modified Aug 13, 2017  46  0  2  0

    First Snippet: How to play with Snip2Code

    This is the first example of a snippet: - the title represents in few words which is the exact issue the snippet resolves; it can be something like the name of a method; - the description (this field) is an optional field where you can add interesting information regarding the snippet; something like the comment on the head of a method; - the c
    /* place here the actual content of your snippet. 
       It should be code or pseudo-code. 
       The less dependencies from external stuff, the better! */

    public by IsCODER modified Mar 20, 2017  807  0  4  0

    Bubble sort in C

    C programming basic by Isfatul Karim
    #include<stdio.h>
    /*
      *Bubble sort
      *Isfatul Karim
    */
    int main()
    {
    	int n;
    	printf("Enter size of array: ");
    	scanf("%d",&n);
    	int l;
    	int data[n];
    	printf("Enter array elements: ");
    	for(l=0;l<n;l++)
    	{
    		scanf("%d",&data[l]);
    	}
    	int i,j;
    	for(i=0;i<n;i++)
    	{
    		for(j=i+1;j<n;j++)
    		{
    			if(data[i]>data[j])
    			{
    				int temp=data[i];
    				data[i]=data[j];
    				data[j]=temp;
    			}
    			else
    			{
    				continue;
    			}
    		}
    	}
    	printf("After bubble sort: \n");
    	for(l=0;l<n;l++)
    	{
    		printf("%d ",data[l]);
    	}
    	return 0;
    }
               

    public by tomsim modified Mar 1, 2017  1951  15  5  0

    Send UDP WOL Magic Package

    C program to send UDP magic package to wake on lan
    /* Compile on Windows:
    cl /nologo /W3 /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_X86_" /link wsock32.lib wol.c
    Compile on linux:
    gcc wol.c -o wol
    
    Change the subnet on line 161 to match your network (sorry!)
    Must configure nic to accept magic package and setup power profile to allow
    wake on lan from nic.  Not for WiFi.
    */
    #ifdef _WIN32
    #define WIN32_LEAN_AND_MEAN
    #include <winsock2.h>
    #else
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <netdb.h>
    #include <arpa/inet.h>
    #endif
    
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #include <errno.h>
    #include <stdarg.h>
    #include <string.h>
    
    #ifdef _WIN32
    #define ERR_RETURN( x, e) if (x == SOCKET_ERROR) { checkError( e); return(0); }
    #else
    #define ERR_RETURN( x, e) if (x < 0) { checkError( e); return(0); }
    #define SOCKET int
    #endif
    
    static int checkError( char *szMsg)
    {
    #ifdef _WIN32
    	int err = WSAGetLastError();
    	if ((err == WSAEINTR) || (err == WSAEWOULDBLOCK) || (err == WSAEINPROGRESS))
    	{
    		printf( "Warning error=%08.8x\n", errno);
    		return 1;
    	}
    	else
    	{
    		printf("Error %d: %s\n", err, szMsg);
    		WSACleanup();
    		return 0;
    	}
    #else
    	perror(szMsg);
    	if ((errno == EINTR) || (errno = EWOULDBLOCK) || (errno == EINPROGRESS))
    		return 1;
    	else
    		return 0;
    #endif
    }
    #ifdef _WIN32
    /*--------------------------------------------------------
      Window socket startup
      --------------------------------------------------------*/
    int socketStartWin32(void)
    {
    	WSADATA wsaData;
    	if (WSAStartup(0x202,&wsaData) == SOCKET_ERROR)
    	{
    		printf("WSAStartup failed with error %d\n",WSAGetLastError());
    		WSACleanup();
    		return -1;
    	}
    	return 0;
    }
    void socketEndWin32(void)
    {
       WSACleanup();
    }
    #endif
    
    /* Magic package format:
    	06 x 255 or (0xff)
    	16 x MAC Address of target PC
    
    */ 
    int main(int argc, char **argv)
    {
    	int i;
    	unsigned char tosend[102];
    	unsigned char mac[6];
    
    	if ((argc < 2) || (strlen(argv[1]) < 17))
    	{
    		printf("Usage wol <mac address aa:bb:cc:dd:ee:ff>\n");
    		exit(0);
    	}
    
    	/** store mac address **/
    	for (i=0; i < sizeof(mac); i++)
    	{
    		char *cp = &argv[1][i*3];
    		mac[i] = 0x00;
    		sscanf(cp,"%2X", (unsigned int *) &mac[i]);
    	}
    	if (argc > 2)	// validate before sent
    	{
    		int ecn = 0;
    		printf( "Send magic package to ");
    		for (i=0; i < sizeof(mac); i++)
    		{
    			if (i) printf(":");
    			printf( "%.2X", mac[i]);
    			if (!mac[i]) ecn++;
    		}
    		printf("\n");
    		if (ecn)
    		{
    			printf("Invalid mac address\n");
    			exit(0);
    		}
    	}
    
    
    	/** first 6 bytes of 255 **/
    	for( i = 0; i < 6; i++) {
    		tosend[i] = 0xFF;
    	}
    	/** append it 16 times to packet **/
    	for( i = 1; i <= 16; i++)
    	{
    		memcpy(&tosend[i * 6], mac, 6 * sizeof(unsigned char));
    	}
    
    #ifdef _WIN32
    	if (socketStartWin32())
    		exit(-1);
    #endif
    	if (1)
    	{
    		int udpSocket;
    		struct sockaddr_in udpClient, udpServer;
    		int broadcast = 1;
    		int rv;
    
    		udpSocket = socket(AF_INET, SOCK_DGRAM, 0);
    
    		/** you need to set this so you can broadcast **/
    		if (setsockopt(udpSocket, SOL_SOCKET, SO_BROADCAST, (char *) &broadcast, sizeof broadcast))
    		{
    			checkError("setsockopt (SO_BROADCAST)");
    			exit(1);
    		}
    		udpClient.sin_family = AF_INET;
    		udpClient.sin_addr.s_addr = INADDR_ANY;
    		udpClient.sin_port = 0;
    
    		bind(udpSocket, (struct sockaddr*)&udpClient, sizeof(udpClient));
    
    		/** …make the packet as shown above **/
    
    		/** set server end point (the broadcast addres)**/
    		udpServer.sin_family = AF_INET;
    		udpServer.sin_addr.s_addr = inet_addr("192.168.1.255");
    		udpServer.sin_port = htons(9);
    
    		/** send the packet **/
    		rv = sendto(udpSocket, tosend, sizeof(unsigned char) * sizeof(tosend), 0, (struct sockaddr*)&udpServer, sizeof(udpServer));
    		if (argc > 2) printf( "Sent %d bytes\n", rv);
    	}
    
    #ifdef _WIN32
    	socketEndWin32();
    #endif
    	return 0;
    }
    
                                        

    public by Nicholas Lydeen modified Aug 29, 2016  254435  0  3  0

    Secure random password generator

    Secure random password generator: mkpw.c
    /*
     * mkpw.c
     * Written by Nicholas Lydeen (nlydeen), 29 August 2016
     * This file is licensed under the terms of the MIT License:                       
     * <https://opensource.org/licenses/MIT>  
     *
     * This program generates a secure random password from ASCII bytes gathered
     * from `/dev/urandom`.
     */
    
    #include <errno.h>
    #include <stddef.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char **argv) {
        int len = 18;
    
        switch(argc) {
        case 2:
            errno = 0;
            char *tmp;
            len = strtol(argv[1], &tmp, 0);
            if(errno || *tmp || len < 1) {
                fprintf(stderr, "`%s` is not a positive integer\n", argv[1]);
                return 1;
            }
        case 1: {
            FILE *fp;
            if(!(fp = fopen("/dev/urandom", "r"))) {
                perror("Could not open `/dev/urandom`");
                return 1;
            }
    
            char *pw = calloc(len + 1, 1);
    
            ptrdiff_t i = 0;
            while(i < len) {
                while(pw[i] < 0x21 || pw[i] > 0x7e)
                    pw[i] = fgetc(fp);
                ++i;
            }
    
            puts(pw);
    
            fclose(fp);
            free(pw);
            break;
        }
        default:
            fprintf(stderr, "Usage: %s [length]\n", argv[0]);
            return 1;
        }
    
        return 0;
    }
    
    
    

    public by tcyrus modified Mar 30, 2016  395  14  3  0

    prayer in c

    prayer in c: prayer.c
    //http://pastebin.com/a2j8tk0B
    #include <stdio.h>
    #include <stdbool.h>
    
    const char* pronoun(int number, bool plural)
    {
        if (number==2) return "you";
        if (!plural) {if (number==1) return "i";}
        else if (number==1) return "we";
        return "they";
    }
    
    void dontthink(char who[100], char auxiliaryVerb[105], bool forgiveNotBelieve)
    {
        printf(", don't think %s %s %s you.\n", who, auxiliaryVerb, forgiveNotBelieve ? "forgive" : "believe");
    }
    
    int main()
    {
        int i, j;
        for (i = 1; i <= 2; i++) {
            for (j = 1;j <= 2; j++) {
                printf("Yah, you never said a word, you didn't send me no letter");
                dontthink(pronoun(1, false), "could", true);
                printf("See, our world is slowly dying and i'm wasting no more time");
                dontthink(pronoun(1, false), "could", false);
            }
            printf("Yah, our hands will get more wrinkled and our hair will be grey");
            dontthink(pronoun(1, false), "could", true);
            printf("And see, the children are starving and their houses were destroyed");
            dontthink(pronoun(3, true), "could", true);
            printf("Hey, when seas will cover lands and when men will be no more");
            dontthink(pronoun(2, false), "can", true);
            printf("Yah, when there'll just be silence and when life will be over");
            dontthink(pronoun(2, false), "will", true);
        }
        return 0;
    }
    
    

    public by DinhoPutz modified Mar 15, 2016  2800  1  5  0

    Media de 10 números digitados em C

    C
    #include <stdio.h>
    #include <stdlib.h>
    #include <conio.h>
    #include <string.h>
    #include <locale.h>
    
    
    int main(void)
    {
    	setlocale(LC_ALL, "Portuguese");
    	int i = 1, ii = 0, numero = 0, total = 0, media = 0;
    
    
    	while (i <= 10)
    	{
    		printf("\n\nDigite o %do numero \n", i);
    		scanf("%d", &numero);
    		
    		i++;
    		total = total + numero;
    		media = total / 10;
    	};
    
    	
    	printf("\nA média é: %d", media);
    	getch();
    	return 0;
    		
    }                        

    public by Rafael G modified Dec 4, 2015  3475  3  3  0

    #sort #sorting #puc apc-b 2016

    #sort #sorting #puc apc-b 2016: mergesort.c
    #include <stdio.h>
    
    void merge(int v[], int inicio, int meio, int fim) {
      int aux[100];
      int aux_inicio = inicio, aux_meio = meio + 1, k=0;
      while(aux_inicio <= meio && aux_meio <= fim)
        if(v[aux_inicio] <= v[aux_meio])
          aux[k++] = v[aux_inicio++];
        else
          aux[k++] = v[aux_meio++];
          
      for(aux_inicio = aux_inicio; aux_inicio <= meio; aux_inicio++)
        aux[k++] = v[aux_inicio];
        
      for(aux_meio = aux_meio; aux_meio <= fim; aux_meio++)
        aux[k++] = v[aux_meio];
        
      k=0;
      
      for(aux_inicio = inicio; aux_inicio <= fim; aux_inicio++) //copia aux para v
        v[aux_inicio] = aux[k++];
    }
    
    void merge_sort(int v[], int inicio, int fim) {
      int meio = (inicio + fim) / 2;
      if(inicio < fim) {
          merge_sort(v, inicio, meio);
          merge_sort(v, meio + 1, fim);
          merge(v, inicio, meio, fim);
        }
    }
    
    int main (void) {
      int var[] = {0, 6, 4, 2, 16, 22, 3, 9};
      merge_sort(var, 0, 7);
      int i;
      for (i = 0; i < 8; i++)
        printf("%d ", var[i]);
      return 0;
    }
    
    

    public by nishrintrunkwala modified Nov 21, 2015  2259  2  5  0

    Function Print snippet

    For debugging and printing the name of the functions in the code
    C
    wmprintf("In %s\r\n", __func__);

    public by Drowze modified Nov 11, 2015  2672  0  3  0

    Only simple letters for now

    Only simple letters for now: caesar.c
    #include <stdio.h>
    
    void caesar_cipher(FILE *input, FILE *output, int k){
      int ch;
      k %= 26; //26 indica uma volta completa, logo qualquer k>26 é excessivo
      do{
        ch = fgetc(input);
        if(ch >= 65 && ch <= 90) { //letra maiuscula? (valores de 'A' e 'Z' da tabela ASCII)
          ch += k;
          if(ch > 90) 
            ch -= 26; //se tiver passado do 'Z', subtrai uma volta completa
        }
        else
          if(ch >= 97 && ch <= 122) { //letra minuscula? (valores de 'a' e 'z' da tabela ASCII)
            ch += k;
            if(ch > 122) 
              ch -= 26; //se tiver passado do 'z', subtrai uma volta completa
          }
        if(ch != EOF)
          fputc(ch, output);
      }while(ch != EOF);
    }
    
    void caesar_decipher(FILE *input, FILE *output, int k){
      int ch;
      k %= 26; //26 indica uma volta completa, logo qualquer k>26 é excessivo
      do{
        ch = fgetc(input);
        if(ch >= 65 && ch <= 90) { //letra maiuscula? (valores de 'A' e 'Z' da tabela ASCII)
          ch -= k;
          if(ch < 65) 
            ch += 26; //se tiver passado do 'A', soma uma volta completa
        }
        else
          if(ch >= 97 && ch <= 122) { //letra minuscula? (valores de 'a' e 'z' da tabela ASCII)
            ch -= k;
            if(ch < 97) 
              ch += 26; //se tiver passado do 'a', soma uma volta completa
          }
        if(ch != EOF)
        fputc(ch, output);
      }while(ch != EOF);
    }
    
    int main(){
      FILE *input = NULL;
      FILE *output = NULL;
      int k = 3;
    
      input = fopen("teste.txt", "r");
      output = fopen("teste_out.txt", "w");
      if(input == NULL || output == NULL){ //se deu erro
        printf("shit");
        return 1;
      }
    
      caesar_cipher(input, output, k); //encripta usando a chave k
      //caesar_cipher(input, output, k); //decripta usando a chave k
      
      fclose(input);
      fclose(output);
    
      return 0;
    }
    
    

    public by David Grayson modified Sep 30, 2015  144621  1  3  0

    Simple Windows C program that connects to a serial port and prints out events from it, such as ring signals.

    Simple Windows C program that connects to a serial port and prints out events from it, such as ring signals.: serial.c
    // Lots of code was copied from https://msdn.microsoft.com/en-us/library/ff802693.aspx#serial_topic3
    
    #include <assert.h>
    #include <windows.h>
    #include <stdio.h>
    #include <stdbool.h>
    
    void ReportStatusEvent(DWORD s)
    {
        if (s == EV_RING)
        {
            printf("ring\n");
        }
        else
        {
            printf("status = 0x%lx\n", s);
        }
    }
    
    int main(int argc, char ** argv)
    {
        if (argc < 2)
        {
            fprintf(stderr, "Need at least one argument to specify the COM port.\n");
            return 1;
        }
    
        HANDLE port = CreateFile(argv[1], GENERIC_READ | GENERIC_WRITE,
            0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
        if (port == INVALID_HANDLE_VALUE)
        {
            DWORD error = GetLastError();
            fprintf(stderr, "Could not open port.  Error 0x%lx.\n", error);
            return 1;
        }
    
        DWORD flags = EV_BREAK | EV_CTS | EV_DSR | EV_ERR | EV_RING |
            EV_RLSD | EV_RXCHAR | EV_RXFLAG | EV_TXEMPTY;
        BOOL success = SetCommMask(port, flags);
        if (!success)
        {
            fprintf(stderr, "Could not set comm mask.\n");
        }
    
        OVERLAPPED osStatus = {0};
        osStatus.hEvent = CreateEvent(NULL, true, false, NULL);
        assert(osStatus.hEvent);
    
        DWORD dwCommEvent;
        BOOL fWaitingOnStat = FALSE;
        while (true)
        {
            // Issue a status event check if one hasn't been issued already.
            if (!fWaitingOnStat)
            {
                //fprintf(stderr, "Calling WaitCommEvent\n");
                if (!WaitCommEvent(port, &dwCommEvent, &osStatus))
                {
                    if (GetLastError() == ERROR_IO_PENDING)
                    {
                        fWaitingOnStat = TRUE;
                        //fprintf(stderr, "WaitCommEvent result is ERROR_IO_PENDING\n");
                    }
                    else
                    {
                        fprintf(stderr, "Error in WaitCommEvent\n");
                        break; // abort
                    }
                }
                else
                {
                    // WaitCommEvent returned immediately.
                    // Deal with status event as appropriate.
                    ReportStatusEvent(dwCommEvent);
                }
            }
    
            // Check on overlapped operation.
            if (fWaitingOnStat)
            {
                DWORD dwOvRes;
    
                // Wait a little while for an event to occur.
                //fprintf(stderr, "Calling WaitForSingleObject\n");
                DWORD dwRes = WaitForSingleObject(osStatus.hEvent, 100);
                switch(dwRes)
                {
                case WAIT_OBJECT_0:
                    // Event occurred.
                    if (!GetOverlappedResult(port, &osStatus, &dwOvRes, FALSE))
                    {
                        // An error occurred in the overlapped operation;
                        // call GetLastError to find out what it was
                        // and abort if it is fatal.
                        fprintf(stderr, "Error from GetOverlappedResult\n");
                    }
                    else
                    {
                        // Status event is stored in the event flag
                        // specified in the original WaitCommEvent call.
                        // Deal with the status event as appropriate.
                        ReportStatusEvent(dwCommEvent);
                    }
    
                    // Set fWaitingOnStat flag to indicate that a new
                    // WaitCommEvent is to be issued.
                    fWaitingOnStat = FALSE;
                    break;
    
                case WAIT_TIMEOUT:
                    // Operation isn't complete yet. fWaitingOnStatusHandle flag
                    // isn't changed since I'll loop back around and I don't want
                    // to issue another WaitCommEvent until the first one finishes.
                    //
                    // This is a good time to do some background work.
                    //fprintf(stderr, "WAIT_TIMEOUT\n");
                    break;
    
                default:
                    // Error in the WaitForSingleObject; abort
                    // This indicates a problem with the OVERLAPPED structure's
                    // event handle.
                    fprintf(stderr, "Error in WaitForSingleObject\n");
                    CloseHandle(osStatus.hEvent);
                    return 70;
                }
            }
        }
    
        return 0;
    }
    
    
    
    • Public Snippets
    • Channels Snippets