#define UNUSED(x) (void)(x)
#include <stdlib.h>
#include <assert.h>
char *getFileContent(char *filename) {
FILE *f = fopen(filename, "rt");
assert(f);
fseek(f, 0, SEEK_END);
size_t length = (size_t) ftell(f);
fseek(f, 0, SEEK_SET);
char *buffer = (char *) malloc(length + 1);
buffer[length] = '\0';
fread(buffer, 1, length, f);
fclose(f);
return buffer;
}
C语言的可变参数函数必须有至少一个固定参数,因为va_start
要以这个参数为基址寻找其他参数。而且函数并不知道传递进来的参数个数,需要自己判断处理
例如:
GLuint createProgram(int count, ...) {
GLuint program = glCreateProgram();
va_list args;
va_start(args, count);
for (int i = 0; i < count; ++i) {
GLuint arg = va_arg(args, GLuint);
glAttachShader(program, arg);
}
va_end(args);
glLinkProgram(program);
return program;
}
#include <stdio.h>
#include <dirent.h>
int main(int argc, char *argv[]) {
struct dirent *cursor;
DIR *dir = opendir(".");
while ((cursor = readdir(dir)) != NULL) {
printf("%s\n", cursor->d_name);
}
closedir(dir);
}
#include <gtk/gtk.h>
int main(int argc, char *argv[]) {
GDir *dir = g_dir_open(".", 0, NULL);
const gchar *filename;
while ((filename = g_dir_read_name(dir))) {
printf("%s\n", filename);
}
}
#include <gtk/gtk.h>
int main(int argc, char *argv[]) {
GDir *dir = g_dir_open("/Users/bj/Dropbox/sample/music", 0, NULL);
const gchar *filename;
GRegex *regex = g_regex_new("(.+)\\.(mp3|wma|ogg)", 0, 0, NULL);
while ((filename = g_dir_read_name(dir))) {
GMatchInfo *matchInfo;
g_regex_match(regex, filename, 0, &matchInfo);
if (g_match_info_matches(matchInfo)) {
printf("Matches: %s\n", g_match_info_fetch(matchInfo, 1));
}
}
}