working on it ...

Filters

Explore Public Snippets

Sort by

Found 20k snippets

    public by rxantos modified Nov 19, 2017  92  0  2  0

    Console Application template windows. Main file.

    Requires stdafx.h
    #include "stdafx.h"
    /**
     * @file
     * @brief Program entry point.
     */
    
    #pragma region Declaration
    /**
     * Program entry point.
     * @param [in] argc Number of arguments.
     * @param [in] argv Arguments.
     * @return 0 on success. 1 - 255 Error code.
     */
    int main(int argc, char * argv[]);
    
    /**
     * Initializes a program.
     * @param [in] argc Number of arguments.
     * @param [in] argv Arguments.
     * @return 0 on success. 1 - 255 Error code.
     */
    static int Init(int argc, const char * argv[]);
    
    /**
     * Cleans up for the program. 
     */
    static void Cleanup(void);
    
    /**
     * Main loop.
     */
    static void MainLoop(void);
    
    #pragma endregion
    
    #pragma region Implementation
    
    int main(int argc, char * argv[])
    {
    	int r = Init(argc, argv);
    	
    	if(!r) {
    		MainLoop();
    	}
    	
    	Cleanup();
    	
    	return r;
    }
    
    static int Init(int argc, const char * argv[])
    {
    	UNREFERENCED_PARAMETER(argc);
    	UNREFERENCED_PARAMETER(argv);
    	return 0;
    }
    
    static void Cleanup(void)
    {
    }
    
    static void MainLoop(void)
    {
    }
    
    #pragma endregion
    

    public by Vikram Dutt modified Jun 26, 2017  26  0  1  0

    Tagged unions (a.k.a variants) in C

    Tagged unions (a.k.a variants) in C: variants.c
    #include <assert.h>
    #include <stddef.h>
    #include <stdio.h>
    
    #define var __auto_type
    #define let __auto_type const
    
    static inline void * variant_cast(void * variant_ptr, ptrdiff_t desired_tag) {
      ptrdiff_t * variant_tag = (ptrdiff_t *)variant_ptr;
      assert(*variant_tag == desired_tag);
      return (void *)((char *)variant_ptr + sizeof(ptrdiff_t));
    }
    
    #define tag(x) ((ptrdiff_t)&Tag##x)
    #define is(x, T) ((x)->tag == tag(T))
    #define as(x, T) ((struct T *)variant_cast((void *)(x), tag(T)))
    
    struct SomeOne {
      int x;
      int y;
    } TagSomeOne;
    
    struct SomeTwo {
      float z;
      float w;
    } TagSomeTwo;
    
    struct Some {
      ptrdiff_t tag;
      union {
        struct SomeOne _;
        struct SomeTwo __;
      };
    };
    
    int main() {
      struct Some a = {};
      a.tag = tag(SomeTwo);
    
      printf("Is `a` tagged as SomeTwo: %d\n", is(&a, SomeTwo));
    
      let b = as(&a, SomeTwo);
      b->w = 5.0;
    
      printf("b->w: %f\n", b->w);
    }
    
    
    

    public by IsCODER modified Mar 20, 2017  853  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  2008  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  254492  2  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  430  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  2836  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 Jerry Jacobs modified Dec 25, 2015  77  0  1  0

    URL shortner implementation in C. This is just an example how it could be implemented. Ideally the lookup table should be pre-generated and not hardcoded.

    URL shortner implementation in C. This is just an example how it could be implemented. Ideally the lookup table should be pre-generated and not hardcoded.: url-shortner.c
    /**
     * Author: Felipe Ferreri Tonello <eu@felipetonello.com>
     *
     * This url-shortner it only works with ASCII characters. It encodes and
     * decodes ids.
     * You can change base_x as you wish.
     *
     * It runs at least 20 times faster then a Python implementation.
     *
     * $ time python url-shortner.py -s I7
     * 1123
     *
     * real    0m0.020s
     * user    0m0.015s
     * sys     0m0.001s
     * $ time ./url-shortner -d I7
     * 1123
     *
     * real    0m0.001s
     * user    0m0.000s
     * sys     0m0.000s
     *
     * But this gain it's not really useful.
     *
     * TODO: use big numbers instead of unsigned long long
     * Compile instructions: gcc url-shortner.c -o url-shortner -lm
     */
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    #include <math.h>
    #include <string.h>
    
    #define BUFFER_SIZE 50
    #define BASE_NUM (sizeof(base_x) / sizeof(*(base_x)))
    #define HASH_BASE_X_SIZE (sizeof(char) * (0xff + 1))
    
    /* NOTE: Ideally you want to generate the lookup table
       and not hard code it. */
    
    /* Base X lookup table */
    static char base_x[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    
    /* Inverted base X lookup table */
    static size_t base_x_to_dec[HASH_BASE_X_SIZE];
    
    /* This is a work around. You should use
       a pre generated lookup table */
    static void init_hash_base_x()
    {
    	size_t i, j;
    
    	for (i = 0; i < HASH_BASE_X_SIZE; ++i)
    		for (j = 0; j < BASE_NUM; ++j)
    			if (i == (size_t) base_x[j]) {
    				base_x_to_dec[i] = j;
    				break;
    			}
    }
    
    inline static swap(char *a, char *b)
    {
    	char tmp = *a;
    	*a = *b;
    	*b = tmp;
    }
    
    static void strrev(char *str, size_t len)
    {
    	size_t i, mid = len / 2;
    
    	for (i = 0; i < mid; ++i)
    		swap(&str[i], &str[len - i - 1]);
    }
    
    unsigned long long decode(char *str)
    {
    	unsigned long long sum = 0;
    	size_t i = 0;
    
    	strrev(str, strlen(str));
    
    	while (*str) {
    		sum += base_x_to_dec[(size_t)*str] * pow(BASE_NUM, i);
    		str++, i++;
    	}
    
    	return sum;
    }
    
    char * encode(unsigned long long id)
    {
    	char *buf = malloc(sizeof(char) * BUFFER_SIZE);
    	size_t i = 0;
    
    	while (id > 0) {
    		int mod = id % BASE_NUM;
    		buf[i] = base_x[mod];
    		id /= BASE_NUM;
    		++i;
    	}
    
    	buf[i] = '\0';
    
    	strrev(buf, i);
    
    	return buf;
    }
    
    void print_usage_and_exit(char *argv0)
    {
    	fprintf(stderr, "usage: %s option value\n"
    	        "Options:\n"
    	        "  -e\tEnconde\n"
    	        "  -d\tDecode\n"
    	        "  -h\tDisplay this information\n", argv0);
    
    	exit(-1);
    }
    
    int main(int argc, char *argv[])
    {
    	if (argc != 3)
    		print_usage_and_exit(argv[0]);
    
    	if(strcmp(argv[1], "-e") == 0) {
    		char *buf = encode(strtoull(argv[2], NULL, 10));
    		printf("%s\n", buf);
    		free(buf);
    
    	} else if(strcmp(argv[1], "-d") == 0) {
    		unsigned long long dec;
    
    		init_hash_base_x();
    
    		dec = decode(argv[2]);
    
    		printf("%llu\n", dec);
    
    	} else {
    		print_usage_and_exit(argv[0]);
    	}
    
    	return 0;
    }
    
    
    

    public by Rafael G modified Dec 4, 2015  3556  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  2291  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 Snippets
    • Channels Snippets