[C/C++标准库]_[初级]_[获取文件的所在目录跨平台实现]


场景:

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)) 
	{
        if (cur == dir)
		{
			//1.根目录
			dir[1] = 0;
		}
		else 
		{
			*cur = 0;
		}
		ret = strdup(dir);
    } 
	else 
	{
		//1.如果是相对路径,获取当前目录
		//io.h
        if (getcwd(dir, 1024) != NULL) 
		{
			dir[1023] = 0;
			ret = strdup(dir);
		}
    }
    return ret;
#undef IS_SEP
}

int main(int argc, char *argv[])
{
	printf("Hello, world\n");
	
	char* dir  = GetFileDirectory("C:\\中文\\adfa\\2.txt");
	printf("dir: %s\n",dir);
	free(dir);

	dir  = GetFileDirectory("C:\\2.txt");
	printf("dir: %s\n",dir);
	free(dir);

	dir  = GetFileDirectory("/Applications/2.txt");
	printf("dir: %s\n",dir);
	free(dir);

	dir  = GetFileDirectory("/2.txt");
	printf("dir: %s\n",dir);
	free(dir);

	dir  = GetFileDirectory("2.txt");
	printf("dir: %s\n",dir);
	free(dir);
	
	return 0;
}

输出:

Hello, world
dir: C:\中文\adfa
dir: C:
dir: /Applications
dir: /
dir: C:\workspace\script-test\test_file

备注: 还是比较高效和实用的,跨平台实现。


你可能感兴趣的:(C++,文件所在目录,GetDirectory)