Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Ubuntu 下讀檔路徑怎麼寫?/ 與 \ 的差別一次說清

我想讀的檔案是 Desktop 下的 test/t.txt,於是就在 Desktop 建了一個 pathTest.cpp。

pathTest.cpp:

#include <stdio.h>
#include <stdlib.h>

int main()
{
 char* path_name = (char*)"./test//t.txt";
 FILE* fp = fopen(path_name, "r");
 if(!fp)
 {
  printf("Open failed!\n");
  exit(-1);
 }
 char str[20];
 fscanf(fp,"%s", str);
 printf("%s\n", str);
 return 0;
}

t.txt:

test!test!test!test!test!

編譯執行都通過。

需要注意的地方

程式很普通,但有個細節以後要留意:在 Ubuntu(其他 Linux 我沒試過)底下,路徑分隔符可以寫 '/' 也可以寫 '//',但絕對不能寫 '\' 或 '\\'。原因在於反斜線會被當成跳脫字元——'\n' 代表換行,而 '\t' 代表定位,只有寫成 '\\' 才會得到真正的反斜線。也就是說,Windows 風格的 ".\test\t.txt" 搬到 Linux 上,路徑早就被跳脫字元破壞掉了。

實務上的建議:路徑一律用正斜線,跨平台也不吃虧;若真的需要反斜線,用原始字串或明確寫成 "\\"。

Copyright © Linux教程網 All Rights Reserved