Skip to content

Instantly share code, notes, and snippets.

@psychoss
Last active January 19, 2016 09:21
Show Gist options
  • Save psychoss/7ce5e8f81143812fc3e5 to your computer and use it in GitHub Desktop.
Save psychoss/7ce5e8f81143812fc3e5 to your computer and use it in GitHub Desktop.
Deal with file system an C language
/* match: search for regexp anywhere in text */
int match(char *regexp, char *text) {
if (regexp[0] == '^')
return matchhere(regexp + 1, text);
do { /* must look even if string is empty */
if (matchhere(regexp, text))
return 1;
} while (*text++ != '\0');
return 0;
}
/* matchhere: search for regexp at beginning of text */
int matchhere(char *regexp, char *text) {
if (regexp[0] == '\0')
return 1;
if (regexp[1] == '*')
return matchstar(regexp[0], regexp + 2, text);
if (regexp[0] == '$' && regexp[1] == '\0')
return *text == '\0';
if (*text != '\0' && (regexp[0] == '.' || regexp[0] == *text))
return matchhere(regexp + 1, text + 1);
return 0;
}
/* matchstar: search for c*regexp at beginning of text */
int matchstar(int c, char *regexp, char *text) {
do { /* a * matches zero or more instances */
if (matchhere(regexp, text))
return 1;
} while (*text != '\0' && (*text++ == c || c == '.'));
return 0;
}
// You must free the result if result is non-NULL.
char *str_replace(char *orig, char *rep, char *with) {
char *result; // the return string
char *ins; // the next insert point
char *tmp; // varies
int len_rep; // length of rep
int len_with; // length of with
int len_front; // distance between rep and end of last rep
int count; // number of replacements
if (!orig)
return NULL;
if (!rep)
rep = "";
len_rep = strlen(rep);
if (!with)
with = "";
len_with = strlen(with);
ins = orig;
for (count = 0; tmp = strstr(ins, rep); ++count) {
ins = tmp + len_rep;
}
// first time through the loop, all the variable are set correctly
// from here on,
// tmp points to the end of the result string
// ins points to the next occurrence of rep in orig
// orig points to the remainder of orig after "end of rep"
tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);
if (!result)
return NULL;
while (count--) {
ins = strstr(orig, rep);
len_front = ins - orig;
tmp = strncpy(tmp, orig, len_front) + len_front;
tmp = strcpy(tmp, with) + len_with;
orig += len_front + len_rep; // move to next "end of rep"
}
strcpy(tmp, orig);
return result;
}
#include <stdio.h>
#include <string.h>
int main(void) {
char str[] = "GET /pub/WWW/TheProject.html HTTP/1.1\r\nHost: www.w3.org\r\n";
char *pch = NULL;
pch = strtok(str, "\r\n");
while (pch != NULL) {
printf("%s\n", pch);
pch = strtok(NULL, "\r\n");
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
char** str_split(char* a_str, const char a_delim)
{
char** result = 0;
size_t count = 0;
char* tmp = a_str;
char* last_comma = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;
/* Count how many elements will be extracted. */
while (*tmp)
{
if (a_delim == *tmp)
{
count++;
last_comma = tmp;
}
tmp++;
}
/* Add space for trailing token. */
count += last_comma < (a_str + strlen(a_str) - 1);
/* Add space for terminating null string so caller
knows where the list of returned strings ends. */
count++;
result = malloc(sizeof(char*) * count);
if (result)
{
size_t idx = 0;
char* token = strtok(a_str, delim);
while (token)
{
assert(idx < count);
*(result + idx++) = strdup(token);
token = strtok(0, delim);
}
assert(idx == count - 1);
*(result + idx) = 0;
}
return result;
}
int main()
{
char months[] = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
char** tokens;
printf("months=[%s]\n\n", months);
tokens = str_split(months, ',');
if (tokens)
{
int i;
for (i = 0; *(tokens + i); i++)
{
printf("month=[%s]\n", *(tokens + i));
free(*(tokens + i));
}
printf("\n");
free(tokens);
}
return 0;
}
#include <string.h>
#include <stdio.h>
#include <stddef.h>
char **strsplit(const char *str, const char *delim, size_t *numtokens) {
char *s = strdup(str);
size_t tokens_alloc = 1;
size_t tokens_used = 0;
char **tokens = calloc(tokens_alloc, sizeof(char *));
char *token, *rest = s;
while ((token = strsep(&rest, delim)) != NULL) {
if (tokens_used == tokens_alloc) {
tokens_alloc *= 2;
tokens = realloc(tokens, tokens_alloc * sizeof(char *));
}
tokens[tokens_used++] = strdup(token);
}
if (tokens_used == 0) {
free(tokens);
tokens = NULL;
} else {
tokens = realloc(tokens, tokens_used * sizeof(char *));
}
*numtokens = tokens_used;
free(s);
return tokens;
}
int main(void) {
size_t numtokens;
char **tokens = strsplit("s sub: ss", "s", &numtokens);
for (size_t i = 0; i < numtokens; i++) {
printf(" token: \"%s\"\n", tokens[i]);
free(tokens[i]);
}
/* char *line = NULL;
size_t linelen;
char **tokens;
size_t numtokens;
while (getline(&line, &linelen, stdin) != -1) {
tokens = strsplit(line, ", \t\n", &numtokens);
for (size_t i = 0; i < numtokens; i++) {
printf(" token: \"%s\"\n", tokens[i]);
free(tokens[i]);
}
if (tokens != NULL)
free(tokens);
}
if (line != NULL) free(line);*/
return 0;
}
// Stores the trimmed input string into the given output buffer, which must be
// large enough to store the result. If it is too small, the output is
// truncated.
size_t trim_not_modified(char *out, size_t len, const char *str) {
if (len == 0)
return 0;
const char *end;
size_t out_size;
// Trim leading space
while (isspace(*str))
str++;
if (*str == 0) // All spaces?
{
*out = 0;
return 1;
}
// Trim trailing space
end = str + strlen(str) - 1;
while (end > str && isspace(*end))
end--;
end++;
// Set output size to minimum of trimmed string length and buffer size minus 1
out_size = (end - str) < len - 1 ? (end - str) : len - 1;
// Copy trimmed string and add null terminator
memcpy(out, str, out_size);
out[out_size] = 0;
return out_size;
}
// Note: This function returns a pointer to a substring of the original string.
// If the given string was allocated dynamically, the caller must not overwrite
// that pointer with the returned value, since the original pointer must be
// deallocated using the same allocator with which it was allocated. The return
// value must NOT be deallocated using free() etc.
char *trim(char *str) {
char *end;
// Trim leading space
while (isspace(*str))
str++;
if (*str == 0) // All spaces?
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while (end > str && isspace(*end))
end--;
// Write new null terminator
*(end + 1) = 0;
return str;
}
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <ftw.h>
#include <sys/stat.h>
#include <string.h>
const char *ext = ".zip";
const char *rep = "-master";
// You must free the result if result is non-NULL.
char *str_replace(char *orig, char *rep, char *with) {
char *result; // the return string
char *ins; // the next insert point
char *tmp; // varies
int len_rep; // length of rep
int len_with; // length of with
int len_front; // distance between rep and end of last rep
int count; // number of replacements
if (!orig)
return NULL;
if (!rep)
rep = "";
len_rep = strlen(rep);
if (!with)
with = "";
len_with = strlen(with);
ins = orig;
for (count = 0; tmp = strstr(ins, rep); ++count) {
ins = tmp + len_rep;
}
// first time through the loop, all the variable are set correctly
// from here on,
// tmp points to the end of the result string
// ins points to the next occurrence of rep in orig
// orig points to the remainder of orig after "end of rep"
tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);
if (!result)
return NULL;
while (count--) {
ins = strstr(orig, rep);
len_front = ins - orig;
tmp = strncpy(tmp, orig, len_front) + len_front;
tmp = strcpy(tmp, with) + len_with;
orig += len_front + len_rep; // move to next "end of rep"
}
strcpy(tmp, orig);
return result;
}
char *strtime(char *ext) {
time_t current_time;
struct tm *struct_time;
time(&current_time);
struct_time = gmtime(&current_time);
char *str = (char *)malloc(20);
snprintf(str, 20, "-%d-%d-%d%s", (struct_time->tm_year + 1900),
(struct_time->tm_mon + 1), struct_time->tm_mday, ext);
return str;
}
// FTW_F The object is a file
// FTW_D ,, ,, ,, ,, directory
// FTW_DNR ,, ,, ,, ,, directory that could not be read
// FTW_SL ,, ,, ,, ,, symbolic link
// FTW_NS The object is NOT a symbolic link and is one for
// which stat() could not be executed
int list(const char *name, const struct stat *status, int type) {
if (type == FTW_NS)
return 0;
if (type == FTW_F) {
char *string = strrchr(name, '.');
if (string != NULL && strcmp(string, ext) == 0) {
char *empty="";
char *str = strtime(ext);
char *r1 = str_replace(name, rep, empty);
char *result = str_replace(r1, ext, str);
free(r1);
if (result != NULL) {
rename(name, result);
free(result);
free(str);
}
}
}
return 0;
}
int main(int argc, char const *argv[]) {
// char *str = strtime("3");
// printf("%s\n", str);
// free(str);
ftw(".", list, 1);
return 0;
}
/*
一个由c/C++编译的程序占用的内存分为以下几个部分
1、栈区(stack)—由编译器自动分配释放,存放函数的参数值,局部变量的值等。其操作方式类似于
数据结构中的栈。
2、堆区(heap)—一般由程序员分配释放,若程序员不释放,程序结束时可能由OS回收。注意它与数据
结构中的堆是两回事,分配方式倒是类似于链表,呵呵。
3、全局区(静态区)(static)—全局变量和静态变量的存储是放在一块的,初始化的全局变量和静态
变量在一块区域,未初始化的全局变量和未初始化的静态变量在相邻的另一块区域。程序结束后由系统
释放。
4、文字常量区—常量字符串就是放在这里的。程序结束后由系统释放。
5、程序代码区
这是一个前辈写的,非常详细
//main.cpp
int a=0; //全局初始化区
char *p1; //全局未初始化区
main()
{
int b;栈
char s[]="abc"; //栈
char *p2; //栈
static int c=0; //全局(静态)初始化区
p1 = (char*)malloc(10);
p2 = (char*)malloc(20); //分配得来得10和20字节的区域就在堆区。
strcpy(p1,"123456");
//123456\0放在常量区,编译器可能会将它与p3所向"123456"优化成一个地方。
}
二、堆和栈的理论知识
2.1申请方式
stack:
由系统自动分配。例如,声明在函数中一个局部变量int b;系统自动在栈中为b开辟空间
heap:
需要程序员自己申请,并指明大小,在c中malloc函数
如p1=(char*)malloc(10);
在C++中用new运算符
如p2=(char*)malloc(10);
但是注意p1、p2本身是在栈中的。
2.2
申请后系统的响应
栈:只要栈的剩余空间大于所申请空间,系统将为程序提供内存,否则将报异常提示栈溢出。
堆:首先应该知道操作系统有一个记录空闲内存地址的链表,当系统收到程序的申请时,
会遍历该链表,寻找第一个空间大于所申请空间的堆结点,然后将该结点从空闲结点链表中删除,并将
该结点的空间分配给程序,另外,对于大多数系统,会在这块内存空间中的首地址处记录本次分配的大
小,这样,代码中的delete语句才能正确的释放本内存空间。另外,由于找到的堆结点的大小不一定正
好等于申请的大小,系统会自动的将多余的那部分重新放入空闲链表中。
2.3申请大小的限制
栈:在Windows下,栈是向低地址扩展的数据结构,是一块连续的内存的区域。这句话的意思是栈顶的地
址和栈的最大容量是系统预先规定好的,在WINDOWS下,栈的大小是2M(也有的说是1M,总之是一个编译
时就确定的常数),如果申请的空间超过栈的剩余空间时,将提示overflow。因此,能从栈获得的空间
较小。
堆:堆是向高地址扩展的数据结构,是不连续的内存区域。这是由于系统是用链表来存储的空闲内存地
址的,自然是不连续的,而链表的遍历方向是由低地址向高地址。堆的大小受限于计算机系统中有效的
虚拟内存。由此可见,堆获得的空间比较灵活,也比较大。
2.4申请效率的比较:
栈:由系统自动分配,速度较快。但程序员是无法控制的。
堆:是由new分配的内存,一般速度比较慢,而且容易产生内存碎片,不过用起来最方便.
另外,在WINDOWS下,最好的方式是用Virtual
Alloc分配内存,他不是在堆,也不是在栈,而是直接在进
程的地址空间中保留一块内存,虽然用起来最不方便。但是速度快,也最灵活。
2.5堆和栈中的存储内容
栈:在函数调用时,第一个进栈的是主函数中后的下一条指令(函数调用语句的下一条可执行语句)的
地址,然后是函数的各个参数,在大多数的C编译器中,参数是由右往左入栈的,然后是函数中的局部变
量。注意静态变量是不入栈的。
当本次函数调用结束后,局部变量先出栈,然后是参数,最后栈顶指针指向最开始存的地址,也就是主
函数中的下一条指令,程序由该点继续运行。
堆:一般是在堆的头部用一个字节存放堆的大小。堆中的具体内容由程序员安排。
2.6存取效率的比较
char s1[]="aaaaaaaaaaaaaaa";
char *s2="bbbbbbbbbbbbbbbbb";
aaaaaaaaaaa是在运行时刻赋值的;
而bbbbbbbbbbb是在编译时就确定的;
但是,在以后的存取中,在栈上的数组比指针所指向的字符串(例如堆)快。
比如:
#include
voidmain()
{
char a=1;
char c[]="1234567890";
char *p="1234567890";
a = c[1];
a = p[1];
return;
}
对应的汇编代码
10:a=c[1];
004010678A4DF1movcl,byteptr[ebp-0Fh]
0040106A884DFCmovbyteptr[ebp-4],cl
11:a=p[1];
0040106D8B55ECmovedx,dwordptr[ebp-14h]
004010708A4201moval,byteptr[edx+1]
004010738845FCmovbyteptr[ebp-4],al
第一种在读取时直接就把字符串中的元素读到寄存器cl中,而第二种则要先把指针值读到edx中,在根据
edx读取字符,显然慢了。
2.7小结:
堆和栈的区别可以用如下的比喻来看出:
使用栈就象我们去饭馆里吃饭,只管点菜(发出申请)、付钱、和吃(使用),吃饱了就走,不必理会
切菜、洗菜等准备工作和洗碗、刷锅等扫尾工作,他的好处是快捷,但是自由度小。
使用堆就象是自己动手做喜欢吃的菜肴,比较麻烦,但是比较符合自己的口味,而且自由度大。
自我总结:
char *c1 =
"abc";实际上先是在文字常量区分配了一块内存放"abc",然后在栈上分配一地址给c1并指向
这块地址,然后改变常量"abc"自然会崩溃
然而char c2[] = "abc",实际上abc分配内存的地方和上者并不一样,可以从
4199056
2293624 看出,完全是两块地方,推断4199056处于常量区,而2293624处于栈区
2293628
2293624
2293620 这段输出看出三个指针分配的区域为栈区,而且是从高地址到低地址
2293620 4199056 abc 看出编译器将c3优化指向常量区的"abc"
继续思考:
代码:
输出:
2293628 4199056 abc
2293624 2293624 abc
2293620 4012976 gbc
写成注释那样,后面改动就会崩溃
可见strcpy(c3,"abc");abc是另一块地方分配的,而且可以改变,和上面的参考文档说法有些不一定,
#include <iostream>
using namespace std;
main()
{
char *c1 = "abc";
char c2[] = "abc";
char *c3 = ( char* )malloc(3);
// *c3 = "abc" //error
strcpy(c3,"abc");
c3[0] = 'g';
printf("%d %d %s\n",&c1,c1,c1);
printf("%d %d %s\n",&c2,c2,c2);
printf("%d %d %s\n",&c3,c3,c3);
getchar();
} */
//var sass = require("node-sass")
var fs = require("fs")
var dir = "/home/psycho/RESOURCE/归档/web/theme/scss"//"/home/psycho/RESOURCE/归档/web/ui/dropdown"//"/home/psycho/RESOURCE/归档/web/static/scss";
var dirjs = "/home/psycho/RESOURCE/归档/web/static/js/app";
var out = '/home/psycho/RESOURCE/归档/web/static/js/index.js';
/*
fs.watch(dir, function(event, filename) {
if (filename === "index.css") {
return
};
console.log(filename)
sass.render({
file: dir + "/index.scss",
outputStyle: "compact"
}, function(err, result) {
if (err) {
console.log(err);
return;
}
fs.writeFile(dir + "/index.css", result.css);
});
})*/
var concating = 0;
fs.watch(dirjs, function(event, filename) {
console.log(event)
if (concating) {
return
};
fs.readdir(dirjs, function(err, files) {
concating = 1
if (err) {
return
};
// files = files.sorf(function(a, b, ) {
// if (a > b) {
// return 1
// };
// if (a < b) {
// return -1
// };
// return 0;
// })
var stream = fs.createWriteStream(out)
files.forEach(function(k){
stream.write(fs.readFileSync(dirjs + "/" + k))
stream.write("\n\n\n");
})
concating = 0;
})
})
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
time_t current_time;
struct tm *struct_time;
time( &current_time);
struct_time = gmtime( &current_time);
char str[15];
sprintf(str, "-%d-%d-%d", (struct_time->tm_year+1900),(struct_time->tm_mon+1),(struct_time->tm_mday));
puts (str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment