场景:
1. 获取文件所在目录便于打开文件所在目录。
2. 需要统计所在目录的文件个数。
3. 需要复制一个备份。
参考: libxml2的xmlParserGetDirectory函数.基本完全参考.添加了一些注释和测试.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>
char *GetFileDirectory(const char *filename) {
char *ret = NULL;
char dir[1024];
char *cur;
if (filename == NULL) return(NULL);
#if defined(WIN32) && !defined(__CYGWIN__)
# define IS_SEP(ch) ((ch=='/')||(ch=='\\'))
#else
# define IS_SEP(ch) (ch=='/')
#endif
strncpy(dir, filename, 1023);
dir[1023] = 0;
cur = &dir[strlen(dir)];
while (cur > dir)
{
if (IS_SEP(*cur)) break;
cur --;
}
if (IS_SEP(*cur))