1.1 小议c++文件流中文件路径
在论坛中闲逛时,经常发现有朋友调试c/c++文件流的代码时,遇到文件路径的问题。下来我结合自己的经验,一起探讨一下。
1.1.1 文件路径的基本概念
OS的文件系统是一个树状结构,有目录、文件的概念。
windows系统的例子:
E:/myprograme/BBG/include/bbg_stl>tree
E:.
│ bbg_stl_config.h
│
├─bbg_list
│ bbg_list.h
│
├─bbg_alloc
│ bbg_allocpool.h
│ bbg_alloc_adapter.h
│ bbg_construct.h
│ bbg_simple_alloc.h
│ bbg_allocator.h
│ bbg_uninitialized.h
│
├─bbg_common
│ bbg_export.h
│ bbg_common.h
│
├─bbg_iterator
│ bbg_iterator.h
│
├─bbg_vector
│ bbg_vector.h
│
├─bbg_type
│ bbg_type_traits.h
│
└─bbg_algorithm
bbg_algorithm.h
linux 系统的例子
yes@yes-desktop:~/myprograme$ find /home/yes/myprograme -type f
/home/yes/myprograme/main
/home/yes/myprograme/test.c
/home/yes/myprograme/tt-v4.7.zip
/home/yes/myprograme/main.cpp
/home/yes/myprograme/test
yes@yes-desktop:~/myprograme$
1.1.1.1 相对路径
“.” 一个“点”代表是当前目录所在的路径。对应着windows示例中的路径是:“E:/myprograme/BBG/include/bbg_stl”
“..” 两个“点”代表,相对于当前目录的上一层目录路径。对应着windowss示例中的路径是:“E:/myprograme/BBG/include”
在UNIX家族、LINUX系统上,“.”和“..”的含义和windows是一样的。这两个路径称为相对路径。
当然类似 “../ /BBG/include” 也是相对路径
1.1.1.2 目录分隔符的问题
从上面的两个示例中,可以发现windows系统的目录分隔符是“/”,而linux系统的目录分隔符是“/”
1.1.1.3 绝对路径
在windows系统中,以盘符开头的路径叫做绝对路径,比如:
“E:/myprograme/BBG/include”
而在linux系统中,“/”开头的路径叫做绝对路径,比如:
“/home/yes/myprograme/test”
注意:“/”是UNIX家族、LINUX所有目录的根目录。
1.1.2 C++文件流的应用
先以几个例子开头吧。
//示例 1
std::ofstream test_1("test_1.txt");
test_1 << "hello world" << std::endl;
test_1.close();
//示例 2
std::ofstream test_2(".//test_2.txt");
test_2 << "hello world" << std::endl;
test_2.close();
//示例 3
std::ofstream test_3("..//test_3.txt");
test_3 << "hello world" << std::endl;
test_3.close();
//示例 4
std::ofstream test_4("d://test_4.txt");
test_4 << "hello world" << std::endl;
test_4.close();
说明:
1、上面示例1、示例2是一样的,代表当前路径下面的文件test_1.txt 和test_2.txt。
2、示例3,是相对于当前路径的上一层目录下面的文件test_3.txt。
3、示例4,是绝对路径,就是d:盘下面的 test_4.txt。
4、在用VS调试的时候,当前路径就是 VS工程文件所在的路径。
5、如果是没有在调试状态下,当前路径就是“可执行文件”(.exe)或者是“动态库”(dll)所在的路径。
现在分别对示例代码进行说明一下,
例如我上面的示例代码保存在下面文件中:
D:/我的文档/Visual Studio 2005/Projects/Test/Test/test/test2.cpp
我的工程文件所在的路径如下:
D:/我的文档/Visual Studio 2005/Projects/Test/Test/Test.vcproj
那么在用VS调试的时候,
示例1和示例2中的test_1.txt 和test_2.txt
就在D:/我的文档/Visual Studio 2005/Projects/Test/Test目录下面
示例3中的test_3.txt在D:/我的文档/Visual Studio 2005/Projects/Test/目录下面。
示例4中的test_4.txt在D:根目录下面
如果我们不是VS调试,直接执行可执行文件,比如,我的可执行文件的路径是:
D:/我的文档/Visual Studio 2005/Projects/Test/debug/ Test.exe
那么,
示例1和示例2中的test_1.txt 和test_2.txt
就在D:/我的文档/Visual Studio 2005/Projects/Test/debug目录下面
示例3中的test_3.txt在D:/我的文档/Visual Studio 2005/Projects/Test目录下面。
示例4中的test_4.txt在D:根目录下面
Windows路径分隔符的说明:
在之前不是说过,windows的路径分隔符用“/”吗?但是上面的最后三个示例,怎么都用“//”呢?
那是因为在字符串中,“/”是一个转义字符表示,必须“//”才能表示一个“/”字符。