C note

· Read in about 1 min · (200 Words)

Language

data types

int(2.3)

const

#define PI 3.1415926

or

const double pi = 3.1415;

char

字符串赋值

char s[10];
strcpy(s,"abcd");
printf("%s, %lu, %lu\n", s, strlen(s), sizeof s); // abcd, 4, 10
// similar to len and cap in Golang

string

strlen()
strcat()
strcmp()
strcpy(dist+n, src)

#include <stdlib.h>
atoi()
atof()
atol()

I/O

fgetc

char file[] = "out.txt";

fprintf(stderr, "Write to file %s\n", file);

FILE *fh_in, *fh_out;

fh_out = fopen(file, "w");
fprintf(fh_out, "some text\nsecond line\n");
if(fclose(fh_out)!=0)
  printf("Error in closing file %s\n", file);

fprintf(stderr, "Read from file %s\n", file);

fh_in = fopen(file, "r");
char c;
while ((c = fgetc(fh_in)) != EOF) {
  printf("%c\n", c);
}

stdin

char c;
while ((c = fgetc(stdin)) != EOF) {
  printf("%c\n", c);
}

fgets

#include <stdio.h>
#define MAXLINE 10
int main(int argc, char **argv) {
  char line[MAXLINE];
  while (fgets(line, MAXLINE, stdin) != NULL && line[0] != '\n')
    fputs(line, stdout);
  return 0;
}

function

先声明

Protect array

int sum(const int ar[]);

struct

cli

ctype.h

isalnum()
isalpha()
isblank()
isdigit()
islower()
isupper()
isspace()
...

template

#include <stdio.h>
#include <stdlib.h> // exit()

void echo(int i) ;

int main(int argc, char *argv[])
{
    int a = 1;
    echo(a);

    int b = 2;
    echo(b);

    return 0;
}

void echo(int i) {
    printf("value: %d\n", i);
}