/usr/include/d/4.8/std/file.d is in libphobos-4.8-dev 4.8.5-4ubuntu8.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 | // Written in the D programming language.
/**
Utilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one _file
at a time. For opening files and manipulating them via handles refer
to module $(LINK2 std_stdio.html,$(D std.stdio)).
Macros:
WIKI = Phobos/StdFile
Copyright: Copyright Digital Mars 2007 - 2011.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(WEB digitalmars.com, Walter Bright),
$(WEB erdani.org, Andrei Alexandrescu),
Jonathan M Davis
Source: $(PHOBOSSRC std/_file.d)
*/
module std.file;
import core.memory;
import core.stdc.stdio, core.stdc.stdlib, core.stdc.string,
core.stdc.errno, std.algorithm, std.array, std.conv,
std.datetime, std.exception, std.format, std.path, std.process,
std.range, std.stdio, std.string, std.traits,
std.typecons, std.typetuple, std.utf;
version (Windows)
{
import core.sys.windows.windows, std.windows.syserror;
}
else version (Posix)
{
import core.sys.posix.dirent, core.sys.posix.fcntl, core.sys.posix.sys.stat,
core.sys.posix.sys.time, core.sys.posix.unistd, core.sys.posix.utime;
}
else
static assert(false, "Module " ~ .stringof ~ " not implemented for this OS.");
version (unittest)
{
import core.thread;
private @property string deleteme() @safe
{
static _deleteme = "deleteme.dmd.unittest.pid";
static _first = true;
if(_first)
{
_deleteme = buildPath(tempDir(), _deleteme) ~ to!string(thisProcessID);
_first = false;
}
return _deleteme;
}
}
// @@@@ TEMPORARY - THIS SHOULD BE IN THE CORE @@@
// {{{
version (Windows)
{
enum FILE_ATTRIBUTE_REPARSE_POINT = 0x400;
// Required by tempPath():
private extern(Windows) DWORD GetTempPathW(DWORD nBufferLength,
LPWSTR lpBuffer);
// Required by rename():
enum MOVEFILE_REPLACE_EXISTING = 1;
private extern(Windows) DWORD MoveFileExW(LPCWSTR lpExistingFileName,
LPCWSTR lpNewFileName,
DWORD dwFlags);
}
else version (Posix)
{
deprecated alias stat_t struct_stat64;
}
// }}}
/++
Exception thrown for file I/O errors.
+/
class FileException : Exception
{
/++
OS error code.
+/
immutable uint errno;
/++
Constructor which takes an error message.
Params:
name = Name of file for which the error occurred.
msg = Message describing the error.
file = The file where the error occurred.
line = The line where the error occurred.
+/
this(in char[] name, in char[] msg, string file = __FILE__, size_t line = __LINE__) @safe pure
{
if(msg.empty)
super(name.idup, file, line);
else
super(text(name, ": ", msg), file, line);
errno = 0;
}
/++
Constructor which takes the error number ($(LUCKY GetLastError)
in Windows, $(D_PARAM errno) in Posix).
Params:
name = Name of file for which the error occurred.
errno = The error number.
file = The file where the error occurred.
Defaults to $(D __FILE__).
line = The line where the error occurred.
Defaults to $(D __LINE__).
+/
version(Windows) this(in char[] name,
uint errno = .GetLastError(),
string file = __FILE__,
size_t line = __LINE__) @safe
{
this(name, sysErrorString(errno), file, line);
this.errno = errno;
}
else version(Posix) this(in char[] name,
uint errno = .errno,
string file = __FILE__,
size_t line = __LINE__) @trusted
{
auto s = strerror(errno);
this(name, to!string(s), file, line);
this.errno = errno;
}
}
private T cenforce(T)(T condition, lazy const(char)[] name, string file = __FILE__, size_t line = __LINE__)
{
if (!condition)
{
version (Windows)
{
throw new FileException(name, .GetLastError(), file, line);
}
else version (Posix)
{
throw new FileException(name, .errno, file, line);
}
}
return condition;
}
/* **********************************
* Basic File operations.
*/
/********************************************
Read entire contents of file $(D name) and returns it as an untyped
array. If the file size is larger than $(D upTo), only $(D upTo)
bytes are read.
Example:
----
import std.file, std.stdio;
void main()
{
auto bytes = cast(ubyte[]) read("filename", 5);
if (bytes.length == 5)
writefln("The fifth byte of the file is 0x%x", bytes[4]);
}
----
Returns: Untyped array of bytes _read.
Throws: $(D FileException) on error.
*/
void[] read(in char[] name, size_t upTo = size_t.max)
{
version(Windows)
{
alias TypeTuple!(GENERIC_READ,
FILE_SHARE_READ, (SECURITY_ATTRIBUTES*).init, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
HANDLE.init)
defaults;
auto h = CreateFileW(std.utf.toUTF16z(name), defaults);
cenforce(h != INVALID_HANDLE_VALUE, name);
scope(exit) cenforce(CloseHandle(h), name);
auto size = GetFileSize(h, null);
cenforce(size != INVALID_FILE_SIZE, name);
size = min(upTo, size);
auto buf = uninitializedArray!(ubyte[])(size);
scope(failure) delete buf;
DWORD numread = void;
cenforce(ReadFile(h,buf.ptr, size, &numread, null) == 1
&& numread == size, name);
return buf[0 .. size];
}
else version(Posix)
{
// A few internal configuration parameters {
enum size_t
minInitialAlloc = 1024 * 4,
maxInitialAlloc = size_t.max / 2,
sizeIncrement = 1024 * 16,
maxSlackMemoryAllowed = 1024;
// }
immutable fd = core.sys.posix.fcntl.open(toStringz(name),
core.sys.posix.fcntl.O_RDONLY);
cenforce(fd != -1, name);
scope(exit) core.sys.posix.unistd.close(fd);
stat_t statbuf = void;
cenforce(fstat(fd, &statbuf) == 0, name);
immutable initialAlloc = to!size_t(statbuf.st_size
? min(statbuf.st_size + 1, maxInitialAlloc)
: minInitialAlloc);
void[] result = uninitializedArray!(ubyte[])(initialAlloc);
scope(failure) delete result;
size_t size = 0;
for (;;)
{
immutable actual = core.sys.posix.unistd.read(fd, result.ptr + size,
min(result.length, upTo) - size);
cenforce(actual != -1, name);
if (actual == 0) break;
size += actual;
if (size < result.length) continue;
immutable newAlloc = size + sizeIncrement;
result = GC.realloc(result.ptr, newAlloc, GC.BlkAttr.NO_SCAN)
[0 .. newAlloc];
}
return result.length - size >= maxSlackMemoryAllowed
? GC.realloc(result.ptr, size, GC.BlkAttr.NO_SCAN)[0 .. size]
: result[0 .. size];
}
}
unittest
{
write(deleteme, "1234");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
assert(read(deleteme, 2) == "12");
assert(read(deleteme) == "1234");
}
version (linux) unittest
{
// A file with "zero" length that doesn't have 0 length at all
auto s = std.file.readText("/proc/sys/kernel/osrelease");
assert(s.length > 0);
//writefln("'%s'", s);
}
/********************************************
Read and validates (using $(XREF utf, validate)) a text file. $(D S)
can be a type of array of characters of any width and constancy. No
width conversion is performed; if the width of the characters in file
$(D name) is different from the width of elements of $(D S),
validation will fail.
Returns: Array of characters read.
Throws: $(D FileException) on file error, $(D UTFException) on UTF
decoding error.
Example:
----
enforce(system("echo abc>deleteme") == 0);
scope(exit) remove("deleteme");
enforce(chomp(readText("deleteme")) == "abc");
----
*/
S readText(S = string)(in char[] name)
{
auto result = cast(S) read(name);
std.utf.validate(result);
return result;
}
unittest
{
write(deleteme, "abc\n");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
enforce(chomp(readText(deleteme)) == "abc");
}
/*********************************************
Write $(D buffer) to file $(D name).
Throws: $(D FileException) on error.
Example:
----
import std.file;
void main()
{
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write("filename", a);
assert(cast(int[]) read("filename") == a);
}
----
*/
void write(in char[] name, const void[] buffer)
{
version(Windows)
{
alias TypeTuple!(GENERIC_WRITE, 0, null, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
HANDLE.init)
defaults;
auto h = CreateFileW(std.utf.toUTF16z(name), defaults);
cenforce(h != INVALID_HANDLE_VALUE, name);
scope(exit) cenforce(CloseHandle(h), name);
DWORD numwritten;
cenforce(WriteFile(h, buffer.ptr, to!DWORD(buffer.length), &numwritten, null) == 1
&& buffer.length == numwritten,
name);
}
else version(Posix)
return writeImpl(name, buffer, O_CREAT | O_WRONLY | O_TRUNC);
}
/*********************************************
Appends $(D buffer) to file $(D name).
Throws: $(D FileException) on error.
Example:
----
import std.file;
void main()
{
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write("filename", a);
int[] b = [ 13, 21 ];
append("filename", b);
assert(cast(int[]) read("filename") == a ~ b);
}
----
*/
void append(in char[] name, in void[] buffer)
{
version(Windows)
{
alias TypeTuple!(GENERIC_WRITE,0,null,OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,HANDLE.init)
defaults;
auto h = CreateFileW(std.utf.toUTF16z(name), defaults);
cenforce(h != INVALID_HANDLE_VALUE, name);
scope(exit) cenforce(CloseHandle(h), name);
DWORD numwritten;
cenforce(SetFilePointer(h, 0, null, FILE_END) != INVALID_SET_FILE_POINTER
&& WriteFile(h,buffer.ptr,to!DWORD(buffer.length),&numwritten,null) == 1
&& buffer.length == numwritten,
name);
}
else version(Posix)
return writeImpl(name, buffer, O_APPEND | O_WRONLY | O_CREAT);
}
// Posix implementation helper for write and append
version(Posix) private void writeImpl(in char[] name,
in void[] buffer, in uint mode)
{
immutable fd = core.sys.posix.fcntl.open(toStringz(name),
mode, octal!666);
cenforce(fd != -1, name);
{
scope(failure) core.sys.posix.unistd.close(fd);
immutable size = buffer.length;
cenforce(
core.sys.posix.unistd.write(fd, buffer.ptr, size) == size,
name);
}
cenforce(core.sys.posix.unistd.close(fd) == 0, name);
}
/***************************************************
* Rename file $(D from) to $(D to).
* If the target file exists, it is overwritten.
* Throws: $(D FileException) on error.
*/
void rename(in char[] from, in char[] to)
{
version(Windows)
{
enforce(MoveFileExW(std.utf.toUTF16z(from), std.utf.toUTF16z(to), MOVEFILE_REPLACE_EXISTING),
new FileException(
text("Attempting to rename file ", from, " to ",
to)));
}
else version(Posix)
cenforce(core.stdc.stdio.rename(toStringz(from), toStringz(to)) == 0, to);
}
unittest
{
auto t1 = deleteme, t2 = deleteme~"2";
scope(exit) foreach (t; [t1, t2]) if (t.exists) t.remove();
write(t1, "1");
rename(t1, t2);
assert(readText(t2) == "1");
write(t1, "2");
rename(t1, t2);
assert(readText(t2) == "2");
}
/***************************************************
Delete file $(D name).
Throws: $(D FileException) on error.
*/
void remove(in char[] name)
{
version(Windows)
{
cenforce(DeleteFileW(std.utf.toUTF16z(name)), name);
}
else version(Posix)
cenforce(core.stdc.stdio.remove(toStringz(name)) == 0,
"Failed to remove file " ~ name);
}
version(Windows) private WIN32_FILE_ATTRIBUTE_DATA getFileAttributesWin(in char[] name)
{
WIN32_FILE_ATTRIBUTE_DATA fad;
enforce(GetFileAttributesExW(std.utf.toUTF16z(name), GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, &fad), new FileException(name.idup));
return fad;
}
version(Windows) private ulong makeUlong(DWORD dwLow, DWORD dwHigh)
{
ULARGE_INTEGER li;
li.LowPart = dwLow;
li.HighPart = dwHigh;
return li.QuadPart;
}
/***************************************************
Get size of file $(D name) in bytes.
Throws: $(D FileException) on error (e.g., file not found).
*/
ulong getSize(in char[] name)
{
version(Windows)
{
with (getFileAttributesWin(name))
return makeUlong(nFileSizeLow, nFileSizeHigh);
}
else version(Posix)
{
stat_t statbuf = void;
cenforce(stat(toStringz(name), &statbuf) == 0, name);
return statbuf.st_size;
}
}
unittest
{
// create a file of size 1
write(deleteme, "a");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
assert(getSize(deleteme) == 1);
// create a file of size 3
write(deleteme, "abc");
assert(getSize(deleteme) == 3);
}
/++
Get the access and modified times of file or folder $(D name).
Params:
name = File/Folder name to get times for.
accessTime = Time the file/folder was last accessed.
modificationTime = Time the file/folder was last modified.
Throws:
$(D FileException) on error.
+/
void getTimes(in char[] name,
out SysTime accessTime,
out SysTime modificationTime)
{
version(Windows)
{
with (getFileAttributesWin(name))
{
accessTime = std.datetime.FILETIMEToSysTime(&ftLastAccessTime);
modificationTime = std.datetime.FILETIMEToSysTime(&ftLastWriteTime);
}
}
else version(Posix)
{
stat_t statbuf = void;
cenforce(stat(toStringz(name), &statbuf) == 0, name);
accessTime = SysTime(unixTimeToStdTime(statbuf.st_atime));
modificationTime = SysTime(unixTimeToStdTime(statbuf.st_mtime));
}
}
unittest
{
auto currTime = Clock.currTime();
write(deleteme, "a");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
SysTime accessTime1 = void;
SysTime modificationTime1 = void;
getTimes(deleteme, accessTime1, modificationTime1);
enum leeway = dur!"seconds"(5);
{
auto diffa = accessTime1 - currTime;
auto diffm = modificationTime1 - currTime;
scope(failure) writefln("[%s] [%s] [%s] [%s] [%s]", accessTime1, modificationTime1, currTime, diffa, diffm);
assert(abs(diffa) <= leeway);
assert(abs(diffm) <= leeway);
}
version(fullFileTests)
{
enum sleepTime = dur!"seconds"(2);
Thread.sleep(sleepTime);
currTime = Clock.currTime();
write(deleteme, "b");
SysTime accessTime2 = void;
SysTime modificationTime2 = void;
getTimes(deleteme, accessTime2, modificationTime2);
{
auto diffa = accessTime2 - currTime;
auto diffm = modificationTime2 - currTime;
scope(failure) writefln("[%s] [%s] [%s] [%s] [%s]", accessTime2, modificationTime2, currTime, diffa, diffm);
//There is no guarantee that the access time will be updated.
assert(abs(diffa) <= leeway + sleepTime);
assert(abs(diffm) <= leeway);
}
assert(accessTime1 <= accessTime2);
assert(modificationTime1 <= modificationTime2);
}
}
/++
$(BLUE This function is Windows-Only.)
Get creation/access/modified times of file $(D name).
This is the same as $(D getTimes) except that it also gives you the file
creation time - which isn't possible on Posix systems.
Params:
name = File name to get times for.
fileCreationTime = Time the file was created.
fileAccessTime = Time the file was last accessed.
fileModificationTime = Time the file was last modified.
Throws:
$(D FileException) on error.
+/
version(StdDdoc) void getTimesWin(in char[] name,
out SysTime fileCreationTime,
out SysTime fileAccessTime,
out SysTime fileModificationTime);
else version(Windows) void getTimesWin(in char[] name,
out SysTime fileCreationTime,
out SysTime fileAccessTime,
out SysTime fileModificationTime)
{
with (getFileAttributesWin(name))
{
fileCreationTime = std.datetime.FILETIMEToSysTime(&ftCreationTime);
fileAccessTime = std.datetime.FILETIMEToSysTime(&ftLastAccessTime);
fileModificationTime = std.datetime.FILETIMEToSysTime(&ftLastWriteTime);
}
}
version(Windows) unittest
{
auto currTime = Clock.currTime();
write(deleteme, "a");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
SysTime creationTime1 = void;
SysTime accessTime1 = void;
SysTime modificationTime1 = void;
getTimesWin(deleteme, creationTime1, accessTime1, modificationTime1);
enum leeway = dur!"seconds"(5);
{
auto diffc = creationTime1 - currTime;
auto diffa = accessTime1 - currTime;
auto diffm = modificationTime1 - currTime;
scope(failure)
{
writefln("[%s] [%s] [%s] [%s] [%s] [%s] [%s]",
creationTime1, accessTime1, modificationTime1, currTime, diffc, diffa, diffm);
}
// Deleting and recreating a file doesn't seem to always reset the "file creation time"
//assert(abs(diffc) <= leeway);
assert(abs(diffa) <= leeway);
assert(abs(diffm) <= leeway);
}
version(fullFileTests)
{
Thread.sleep(dur!"seconds"(2));
currTime = Clock.currTime();
write(deleteme, "b");
SysTime creationTime2 = void;
SysTime accessTime2 = void;
SysTime modificationTime2 = void;
getTimesWin(deleteme, creationTime2, accessTime2, modificationTime2);
{
auto diffa = accessTime2 - currTime;
auto diffm = modificationTime2 - currTime;
scope(failure)
{
writefln("[%s] [%s] [%s] [%s] [%s]",
accessTime2, modificationTime2, currTime, diffa, diffm);
}
assert(abs(diffa) <= leeway);
assert(abs(diffm) <= leeway);
}
assert(creationTime1 == creationTime2);
assert(accessTime1 <= accessTime2);
assert(modificationTime1 <= modificationTime2);
}
}
/++
Set access/modified times of file or folder $(D name).
Params:
name = File/Folder name to get times for.
accessTime = Time the file/folder was last accessed.
modificationTime = Time the file/folder was last modified.
Throws:
$(D FileException) on error.
+/
void setTimes(in char[] name,
SysTime accessTime,
SysTime modificationTime)
{
version(Windows)
{
const ta = SysTimeToFILETIME(accessTime);
const tm = SysTimeToFILETIME(modificationTime);
alias TypeTuple!(GENERIC_WRITE,
0,
null,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL |
FILE_ATTRIBUTE_DIRECTORY |
FILE_FLAG_BACKUP_SEMANTICS,
HANDLE.init)
defaults;
auto h = CreateFileW(std.utf.toUTF16z(name), defaults);
cenforce(h != INVALID_HANDLE_VALUE, name);
scope(exit)
cenforce(CloseHandle(h), name);
cenforce(SetFileTime(h, null, &ta, &tm), name);
}
else version(Posix)
{
timeval[2] t = void;
t[0] = accessTime.toTimeVal();
t[1] = modificationTime.toTimeVal();
cenforce(utimes(toStringz(name), t) == 0, name);
}
}
unittest
{
string dir = deleteme ~ r".dir/a/b/c";
string file = dir ~ "/file";
if (!exists(dir)) mkdirRecurse(dir);
{ auto f = File(file, "w"); }
foreach (path; [file, dir]) // test file and dir
{
SysTime atime = SysTime(DateTime(2010, 10, 4, 0, 0, 30));
SysTime mtime = SysTime(DateTime(2011, 10, 4, 0, 0, 30));
setTimes(path, atime, mtime);
SysTime atime_res;
SysTime mtime_res;
getTimes(path, atime_res, mtime_res);
assert(atime == atime_res);
assert(mtime == mtime_res);
}
rmdirRecurse(dir);
}
/++
Returns the time that the given file was last modified.
Throws:
$(D FileException) if the given file does not exist.
+/
SysTime timeLastModified(in char[] name)
{
version(Windows)
{
SysTime dummy = void;
SysTime ftm = void;
getTimesWin(name, dummy, dummy, ftm);
return ftm;
}
else version(Posix)
{
stat_t statbuf = void;
cenforce(stat(toStringz(name), &statbuf) == 0, name);
return SysTime(unixTimeToStdTime(statbuf.st_mtime));
}
}
/++
Returns the time that the given file was last modified. If the
file does not exist, returns $(D returnIfMissing).
A frequent usage pattern occurs in build automation tools such as
$(WEB gnu.org/software/make, make) or $(WEB
en.wikipedia.org/wiki/Apache_Ant, ant). To check whether file $(D
target) must be rebuilt from file $(D source) (i.e., $(D target) is
older than $(D source) or does not exist), use the comparison
below. The code throws a $(D FileException) if $(D source) does not
exist (as it should). On the other hand, the $(D SysTime.min) default
makes a non-existing $(D target) seem infinitely old so the test
correctly prompts building it.
Params:
name = The name of the file to get the modification time for.
returnIfMissing = The time to return if the given file does not exist.
Examples:
--------------------
if(timeLastModified(source) >= timeLastModified(target, SysTime.min))
{
// must (re)build
}
else
{
// target is up-to-date
}
--------------------
+/
SysTime timeLastModified(in char[] name, SysTime returnIfMissing)
{
version(Windows)
{
if(!exists(name))
return returnIfMissing;
SysTime dummy = void;
SysTime ftm = void;
getTimesWin(name, dummy, dummy, ftm);
return ftm;
}
else version(Posix)
{
stat_t statbuf = void;
return stat(toStringz(name), &statbuf) != 0 ?
returnIfMissing :
SysTime(unixTimeToStdTime(statbuf.st_mtime));
}
}
unittest
{
//std.process.system("echo a > deleteme") == 0 || assert(false);
if(exists(deleteme))
remove(deleteme);
write(deleteme, "a\n");
scope(exit)
{
assert(exists(deleteme));
remove(deleteme);
}
// assert(lastModified("deleteme") >
// lastModified("this file does not exist", SysTime.min));
//assert(lastModified("deleteme") > lastModified(__FILE__));
}
/++
Returns whether the given file (or directory) exists.
+/
bool exists(in char[] name) @trusted
{
version(Windows)
{
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/
// fileio/base/getfileattributes.asp
return GetFileAttributesW(std.utf.toUTF16z(name)) != 0xFFFFFFFF;
}
else version(Posix)
{
/*
The reason why we use stat (and not access) here is
the quirky behavior of access for SUID programs: if
we used access, a file may not appear to "exist",
despite that the program would be able to open it
just fine. The behavior in question is described as
follows in the access man page:
> The check is done using the calling process's real
> UID and GID, rather than the effective IDs as is
> done when actually attempting an operation (e.g.,
> open(2)) on the file. This allows set-user-ID
> programs to easily determine the invoking user's
> authority.
While various operating systems provide eaccess or
euidaccess functions, these are not part of POSIX -
so it's safer to use stat instead.
*/
stat_t statbuf = void;
return stat(toStringz(name), &statbuf) == 0;
}
}
unittest
{
assert(exists("."));
assert(!exists("this file does not exist"));
write(deleteme, "a\n");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
assert(exists(deleteme));
}
/++
Returns the attributes of the given file.
Note that the file attributes on Windows and Posix systems are
completely different. On Windows, they're what is returned by $(WEB
msdn.microsoft.com/en-us/library/aa364944(v=vs.85).aspx,
GetFileAttributes), whereas on Posix systems, they're the $(LUCKY
st_mode) value which is part of the $(D stat struct) gotten by
calling the $(WEB en.wikipedia.org/wiki/Stat_%28Unix%29, $(D stat))
function.
On Posix systems, if the given file is a symbolic link, then
attributes are the attributes of the file pointed to by the symbolic
link.
Params:
name = The file to get the attributes of.
Throws: $(D FileException) on error.
+/
uint getAttributes(in char[] name)
{
version(Windows)
{
immutable result = GetFileAttributesW(std.utf.toUTF16z(name));
enforce(result != uint.max, new FileException(name.idup));
return result;
}
else version(Posix)
{
stat_t statbuf = void;
cenforce(stat(toStringz(name), &statbuf) == 0, name);
return statbuf.st_mode;
}
}
/++
If the given file is a symbolic link, then this returns the attributes of the
symbolic link itself rather than file that it points to. If the given file
is $(I not) a symbolic link, then this function returns the same result
as getAttributes.
On Windows, getLinkAttributes is identical to getAttributes. It exists on
Windows so that you don't have to special-case code for Windows when dealing
with symbolic links.
Params:
name = The file to get the symbolic link attributes of.
Throws:
$(D FileException) on error.
+/
uint getLinkAttributes(in char[] name)
{
version(Windows)
{
return getAttributes(name);
}
else version(Posix)
{
stat_t lstatbuf = void;
cenforce(lstat(toStringz(name), &lstatbuf) == 0, name);
return lstatbuf.st_mode;
}
}
/++
Returns whether the given file is a directory.
Params:
name = The path to the file.
Throws:
$(D FileException) if the given file does not exist.
Examples:
--------------------
assert(!"/etc/fonts/fonts.conf".isDir);
assert("/usr/share/include".isDir);
--------------------
+/
@property bool isDir(in char[] name)
{
version(Windows)
{
return (getAttributes(name) & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
else version(Posix)
{
return (getAttributes(name) & S_IFMT) == S_IFDIR;
}
}
unittest
{
version(Windows)
{
if("C:\\Program Files\\".exists)
assert("C:\\Program Files\\".isDir);
if("C:\\Windows\\system.ini".exists)
assert(!"C:\\Windows\\system.ini".isDir);
}
else version(Posix)
{
if("/usr/include".exists)
assert("/usr/include".isDir);
if("/usr/include/assert.h".exists)
assert(!"/usr/include/assert.h".isDir);
}
}
/++
Returns whether the given file attributes are for a directory.
Params:
attributes = The file attributes.
Examples:
--------------------
assert(!attrIsDir(getAttributes("/etc/fonts/fonts.conf")));
assert(!attrIsDir(getLinkAttributes("/etc/fonts/fonts.conf")));
--------------------
+/
bool attrIsDir(uint attributes) nothrow
{
version(Windows)
{
return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
else version(Posix)
{
return (attributes & S_IFMT) == S_IFDIR;
}
}
unittest
{
version(Windows)
{
if("C:\\Program Files\\".exists)
{
assert(attrIsDir(getAttributes("C:\\Program Files\\")));
assert(attrIsDir(getLinkAttributes("C:\\Program Files\\")));
}
if("C:\\Windows\\system.ini".exists)
{
assert(!attrIsDir(getAttributes("C:\\Windows\\system.ini")));
assert(!attrIsDir(getLinkAttributes("C:\\Windows\\system.ini")));
}
}
else version(Posix)
{
if("/usr/include".exists)
{
assert(attrIsDir(getAttributes("/usr/include")));
assert(attrIsDir(getLinkAttributes("/usr/include")));
}
if("/usr/include/assert.h".exists)
{
assert(!attrIsDir(getAttributes("/usr/include/assert.h")));
assert(!attrIsDir(getLinkAttributes("/usr/include/assert.h")));
}
}
}
/++
Returns whether the given file (or directory) is a file.
On Windows, if a file is not a directory, then it's a file. So,
either $(D isFile) or $(D isDir) will return true for any given file.
On Posix systems, if $(D isFile) is $(D true), that indicates that the file
is a regular file (e.g. not a block not device). So, on Posix systems, it's
possible for both $(D isFile) and $(D isDir) to be $(D false) for a
particular file (in which case, it's a special file). You can use
$(D getAttributes) to get the attributes to figure out what type of special
it is, or you can use $(D DirEntry) to get at its $(D statBuf), which is the
result from $(D stat). In either case, see the man page for $(D stat) for
more information.
Params:
name = The path to the file.
Throws:
$(D FileException) if the given file does not exist.
Examples:
--------------------
assert("/etc/fonts/fonts.conf".isFile);
assert(!"/usr/share/include".isFile);
--------------------
+/
@property bool isFile(in char[] name)
{
version(Windows)
return !name.isDir;
else version(Posix)
return (getAttributes(name) & S_IFMT) == S_IFREG;
}
unittest
{
version(Windows)
{
if("C:\\Program Files\\".exists)
assert(!"C:\\Program Files\\".isFile);
if("C:\\Windows\\system.ini".exists)
assert("C:\\Windows\\system.ini".isFile);
}
else version(Posix)
{
if("/usr/include".exists)
assert(!"/usr/include".isFile);
if("/usr/include/assert.h".exists)
assert("/usr/include/assert.h".isFile);
}
}
/++
Returns whether the given file attributes are for a file.
On Windows, if a file is not a directory, it's a file. So, either
$(D attrIsFile) or $(D attrIsDir) will return $(D true) for the
attributes of any given file.
On Posix systems, if $(D attrIsFile) is $(D true), that indicates that the
file is a regular file (e.g. not a block not device). So, on Posix systems,
it's possible for both $(D attrIsFile) and $(D attrIsDir) to be $(D false)
for a particular file (in which case, it's a special file). If a file is a
special file, you can use the attributes to check what type of special file
it is (see the man page for $(D stat) for more information).
Params:
attributes = The file attributes.
Examples:
--------------------
assert(attrIsFile(getAttributes("/etc/fonts/fonts.conf")));
assert(attrIsFile(getLinkAttributes("/etc/fonts/fonts.conf")));
--------------------
+/
bool attrIsFile(uint attributes) nothrow
{
version(Windows)
{
return (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
}
else version(Posix)
{
return (attributes & S_IFMT) == S_IFREG;
}
}
unittest
{
version(Windows)
{
if("C:\\Program Files\\".exists)
{
assert(!attrIsFile(getAttributes("C:\\Program Files\\")));
assert(!attrIsFile(getLinkAttributes("C:\\Program Files\\")));
}
if("C:\\Windows\\system.ini".exists)
{
assert(attrIsFile(getAttributes("C:\\Windows\\system.ini")));
assert(attrIsFile(getLinkAttributes("C:\\Windows\\system.ini")));
}
}
else version(Posix)
{
if("/usr/include".exists)
{
assert(!attrIsFile(getAttributes("/usr/include")));
assert(!attrIsFile(getLinkAttributes("/usr/include")));
}
if("/usr/include/assert.h".exists)
{
assert(attrIsFile(getAttributes("/usr/include/assert.h")));
assert(attrIsFile(getLinkAttributes("/usr/include/assert.h")));
}
}
}
/++
Returns whether the given file is a symbolic link.
On Windows, returns $(D true) when the file is either a symbolic link or a
junction point.
Params:
name = The path to the file.
Throws:
$(D FileException) if the given file does not exist.
+/
@property bool isSymlink(C)(const(C)[] name)
{
version(Windows)
return (getAttributes(name) & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
else version(Posix)
return (getLinkAttributes(name) & S_IFMT) == S_IFLNK;
}
unittest
{
version(Windows)
{
if("C:\\Program Files\\".exists)
assert(!"C:\\Program Files\\".isSymlink);
if("C:\\Users\\".exists && "C:\\Documents and Settings\\".exists)
assert("C:\\Documents and Settings\\".isSymlink);
enum fakeSymFile = "C:\\Windows\\system.ini";
if(fakeSymFile.exists)
{
assert(!fakeSymFile.isSymlink);
assert(!fakeSymFile.isSymlink);
assert(!attrIsSymlink(getAttributes(fakeSymFile)));
assert(!attrIsSymlink(getLinkAttributes(fakeSymFile)));
assert(attrIsFile(getAttributes(fakeSymFile)));
assert(attrIsFile(getLinkAttributes(fakeSymFile)));
assert(!attrIsDir(getAttributes(fakeSymFile)));
assert(!attrIsDir(getLinkAttributes(fakeSymFile)));
assert(getAttributes(fakeSymFile) == getLinkAttributes(fakeSymFile));
}
}
else version(Posix)
{
if("/usr/include".exists)
{
assert(!"/usr/include".isSymlink);
immutable symfile = deleteme ~ "_slink\0";
scope(exit) if(symfile.exists) symfile.remove();
core.sys.posix.unistd.symlink("/usr/include", symfile.ptr);
assert(symfile.isSymlink);
assert(!attrIsSymlink(getAttributes(symfile)));
assert(attrIsSymlink(getLinkAttributes(symfile)));
assert(attrIsDir(getAttributes(symfile)));
assert(!attrIsDir(getLinkAttributes(symfile)));
assert(!attrIsFile(getAttributes(symfile)));
assert(!attrIsFile(getLinkAttributes(symfile)));
}
if("/usr/include/assert.h".exists)
{
assert(!"/usr/include/assert.h".isSymlink);
immutable symfile = deleteme ~ "_slink\0";
scope(exit) if(symfile.exists) symfile.remove();
core.sys.posix.unistd.symlink("/usr/include/assert.h", symfile.ptr);
assert(symfile.isSymlink);
assert(!attrIsSymlink(getAttributes(symfile)));
assert(attrIsSymlink(getLinkAttributes(symfile)));
assert(!attrIsDir(getAttributes(symfile)));
assert(!attrIsDir(getLinkAttributes(symfile)));
assert(attrIsFile(getAttributes(symfile)));
assert(!attrIsFile(getLinkAttributes(symfile)));
}
}
}
/++
Returns whether the given file attributes are for a symbolic link.
On Windows, return $(D true) when the file is either a symbolic link or a
junction point.
Params:
attributes = The file attributes.
Examples:
--------------------
core.sys.posix.unistd.symlink("/etc/fonts/fonts.conf", "/tmp/alink");
assert(!getAttributes("/tmp/alink").isSymlink);
assert(getLinkAttributes("/tmp/alink").isSymlink);
--------------------
+/
bool attrIsSymlink(uint attributes) nothrow
{
version(Windows)
return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
else version(Posix)
return (attributes & S_IFMT) == S_IFLNK;
}
/****************************************************
* Change directory to $(D pathname).
* Throws: $(D FileException) on error.
*/
void chdir(in char[] pathname)
{
version(Windows)
{
enforce(SetCurrentDirectoryW(std.utf.toUTF16z(pathname)),
new FileException(pathname.idup));
}
else version(Posix)
{
cenforce(core.sys.posix.unistd.chdir(toStringz(pathname)) == 0,
pathname);
}
}
/****************************************************
Make directory $(D pathname).
Throws: $(D FileException) on error.
*/
void mkdir(in char[] pathname)
{
version(Windows)
{
enforce(CreateDirectoryW(std.utf.toUTF16z(pathname), null),
new FileException(pathname.idup));
}
else version(Posix)
{
cenforce(core.sys.posix.sys.stat.mkdir(toStringz(pathname), octal!777) == 0,
pathname);
}
}
/****************************************************
* Make directory and all parent directories as needed.
*
* Throws: $(D FileException) on error.
*/
void mkdirRecurse(in char[] pathname)
{
const left = dirName(pathname);
if (!exists(left))
{
version (Windows)
{ /* Prevent infinite recursion if left is "d:\" and
* drive d does not exist.
*/
if (left.length >= 3 && left[$ - 2] == ':')
throw new FileException(left.idup);
}
mkdirRecurse(left);
}
if (!baseName(pathname).empty)
{
mkdir(pathname);
}
}
unittest
{
// bug3570
{
immutable basepath = deleteme ~ "_dir";
version (Windows)
{
immutable path = basepath ~ "\\fake\\here\\";
}
else version (Posix)
{
immutable path = basepath ~ `/fake/here/`;
}
mkdirRecurse(path);
assert(basepath.exists && basepath.isDir);
scope(exit) rmdirRecurse(basepath);
assert(path.exists && path.isDir);
}
}
/****************************************************
Remove directory $(D pathname).
Throws: $(D FileException) on error.
*/
void rmdir(in char[] pathname)
{
version(Windows)
{
cenforce(RemoveDirectoryW(std.utf.toUTF16z(pathname)),
pathname);
}
else version(Posix)
{
cenforce(core.sys.posix.unistd.rmdir(toStringz(pathname)) == 0,
pathname);
}
}
/++
$(BLUE This function is Posix-Only.)
Creates a symlink.
Params:
original = The file to link from.
link = The symlink to create.
Note:
Relative paths are relative to the current working directory,
not the files being linked to or from.
Throws:
$(D FileException) on error (which includes if the symlink already
exists).
+/
version(StdDdoc) void symlink(C1, C2)(const(C1)[] original, const(C2)[] link);
else version(Posix) void symlink(C1, C2)(const(C1)[] original, const(C2)[] link)
{
cenforce(core.sys.posix.unistd.symlink(toUTFz!(const char*)(original),
toUTFz!(const char*)(link)) == 0,
link);
}
version(Posix) unittest
{
if("/usr/include".exists)
{
immutable symfile = deleteme ~ "_slink\0";
scope(exit) if(symfile.exists) symfile.remove();
symlink("/usr/include", symfile);
assert(symfile.exists);
assert(symfile.isSymlink);
assert(!attrIsSymlink(getAttributes(symfile)));
assert(attrIsSymlink(getLinkAttributes(symfile)));
assert(attrIsDir(getAttributes(symfile)));
assert(!attrIsDir(getLinkAttributes(symfile)));
assert(!attrIsFile(getAttributes(symfile)));
assert(!attrIsFile(getLinkAttributes(symfile)));
}
if("/usr/include/assert.h".exists)
{
assert(!"/usr/include/assert.h".isSymlink);
immutable symfile = deleteme ~ "_slink\0";
scope(exit) if(symfile.exists) symfile.remove();
symlink("/usr/include/assert.h", symfile);
assert(symfile.exists);
assert(symfile.isSymlink);
assert(!attrIsSymlink(getAttributes(symfile)));
assert(attrIsSymlink(getLinkAttributes(symfile)));
assert(!attrIsDir(getAttributes(symfile)));
assert(!attrIsDir(getLinkAttributes(symfile)));
assert(attrIsFile(getAttributes(symfile)));
assert(!attrIsFile(getLinkAttributes(symfile)));
}
}
/++
$(BLUE This function is Posix-Only.)
Returns the path to the file pointed to by a symlink. Note that the
path could be either relative or absolute depending on the symlink.
If the path is relative, it's relative to the symlink, not the current
working directory.
Throws:
$(D FileException) on error.
+/
version(StdDdoc) string readLink(C)(const(C)[] link);
else version(Posix) string readLink(C)(const(C)[] link)
{
enum bufferLen = 2048;
enum maxCodeUnits = 6;
char[bufferLen] buffer;
auto linkPtr = toUTFz!(const char*)(link);
auto size = core.sys.posix.unistd.readlink(linkPtr,
buffer.ptr,
buffer.length);
cenforce(size != -1, link);
if(size <= bufferLen - maxCodeUnits)
return to!string(buffer[0 .. size]);
auto dynamicBuffer = new char[](bufferLen * 3 / 2);
foreach(i; 0 .. 10)
{
size = core.sys.posix.unistd.readlink(linkPtr,
dynamicBuffer.ptr,
dynamicBuffer.length);
cenforce(size != -1, link);
if(size <= dynamicBuffer.length - maxCodeUnits)
{
dynamicBuffer.length = size;
return assumeUnique(dynamicBuffer);
}
dynamicBuffer.length = dynamicBuffer.length * 3 / 2;
}
throw new FileException(to!string(link), "Path is too long to read.");
}
version(Posix) unittest
{
foreach(file; ["/usr/include", "/usr/include/assert.h"])
{
if(file.exists)
{
immutable symfile = deleteme ~ "_slink\0";
scope(exit) if(symfile.exists) symfile.remove();
symlink(file, symfile);
assert(readLink(symfile) == file, format("Failed file: %s", file));
}
}
assertThrown!FileException(readLink("/doesnotexist"));
}
/****************************************************
* Get current directory.
* Throws: $(D FileException) on error.
*/
version(Windows) string getcwd()
{
/* GetCurrentDirectory's return value:
1. function succeeds: the number of characters that are written to
the buffer, not including the terminating null character.
2. function fails: zero
3. the buffer (lpBuffer) is not large enough: the required size of
the buffer, in characters, including the null-terminating character.
*/
wchar[4096] buffW = void; //enough for most common case
immutable n = cenforce(GetCurrentDirectoryW(to!DWORD(buffW.length), buffW.ptr),
"getcwd");
// we can do it because toUTFX always produces a fresh string
if(n < buffW.length)
{
return toUTF8(buffW[0 .. n]);
}
else //staticBuff isn't enough
{
auto ptr = cast(wchar*) malloc(wchar.sizeof * n);
scope(exit) free(ptr);
immutable n2 = GetCurrentDirectoryW(n, ptr);
cenforce(n2 && n2 < n, "getcwd");
return toUTF8(ptr[0 .. n2]);
}
}
else version (Posix) string getcwd()
{
auto p = cenforce(core.sys.posix.unistd.getcwd(null, 0),
"cannot get cwd");
scope(exit) core.stdc.stdlib.free(p);
return p[0 .. core.stdc.string.strlen(p)].idup;
}
unittest
{
auto s = getcwd();
assert(s.length);
}
version (OSX)
private extern (C) int _NSGetExecutablePath(char* buf, uint* bufsize);
else version (FreeBSD)
private extern (C) int sysctl (const int* name, uint namelen, void* oldp,
size_t* oldlenp, const void* newp, size_t newlen);
/**
* Returns the full path of the current executable.
*
* Throws:
* $(XREF object, Exception)
*/
@trusted string thisExePath ()
{
version (OSX)
{
import core.sys.posix.stdlib : realpath;
uint size;
_NSGetExecutablePath(null, &size); // get the length of the path
auto buffer = new char[size];
_NSGetExecutablePath(buffer.ptr, &size);
auto absolutePath = realpath(buffer.ptr, null); // let the function allocate
scope (exit)
{
if (absolutePath)
free(absolutePath);
}
errnoEnforce(absolutePath);
return to!(string)(absolutePath);
}
else version (linux)
{
return readLink("/proc/self/exe");
}
else version (Windows)
{
wchar[MAX_PATH] buf;
wchar[] buffer = buf[];
while (true)
{
auto len = GetModuleFileNameW(null, buffer.ptr, cast(DWORD) buffer.length);
enforce(len, sysErrorString(GetLastError()));
if (len != buffer.length)
return to!(string)(buffer[0 .. len]);
buffer.length *= 2;
}
}
else version (FreeBSD)
{
enum
{
CTL_KERN = 1,
KERN_PROC = 14,
KERN_PROC_PATHNAME = 12
}
int[4] mib = [CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1];
size_t len;
auto result = sysctl(mib.ptr, mib.length, null, &len, null, 0); // get the length of the path
errnoEnforce(result == 0);
auto buffer = new char[len - 1];
result = sysctl(mib.ptr, mib.length, buffer.ptr, &len, null, 0);
errnoEnforce(result == 0);
return buffer.assumeUnique;
}
else
static assert(0, "thisExePath is not supported on this platform");
}
unittest
{
auto path = thisExePath();
assert(path.exists);
assert(path.isAbsolute);
assert(path.isFile);
}
version(StdDdoc)
{
/++
Info on a file, similar to what you'd get from stat on a Posix system.
+/
struct DirEntry
{
/++
Constructs a DirEntry for the given file (or directory).
Params:
path = The file (or directory) to get a DirEntry for.
Throws:
$(D FileException) if the file does not exist.
+/
this(string path);
version (Windows)
{
private this(string path, in WIN32_FIND_DATA* fd);
private this(string path, in WIN32_FIND_DATAW *fd);
}
else version (Posix)
{
private this(string path, core.sys.posix.dirent.dirent* fd);
}
/++
Returns the path to the file represented by this $(D DirEntry).
Examples:
--------------------
auto de1 = DirEntry("/etc/fonts/fonts.conf");
assert(de1.name == "/etc/fonts/fonts.conf");
auto de2 = DirEntry("/usr/share/include");
assert(de2.name == "/usr/share/include");
--------------------
+/
@property string name() const;
/++
Returns whether the file represented by this $(D DirEntry) is a
directory.
Examples:
--------------------
auto de1 = DirEntry("/etc/fonts/fonts.conf");
assert(!de1.isDir);
auto de2 = DirEntry("/usr/share/include");
assert(de2.isDir);
--------------------
+/
@property bool isDir();
/++
Returns whether the file represented by this $(D DirEntry) is a file.
On Windows, if a file is not a directory, then it's a file. So,
either $(D isFile) or $(D isDir) will return $(D true).
On Posix systems, if $(D isFile) is $(D true), that indicates that
the file is a regular file (e.g. not a block not device). So, on
Posix systems, it's possible for both $(D isFile) and $(D isDir) to
be $(D false) for a particular file (in which case, it's a special
file). You can use $(D attributes) or $(D statBuf) to get more
information about a special file (see the stat man page for more
details).
Examples:
--------------------
auto de1 = DirEntry("/etc/fonts/fonts.conf");
assert(de1.isFile);
auto de2 = DirEntry("/usr/share/include");
assert(!de2.isFile);
--------------------
+/
@property bool isFile();
/++
Returns whether the file represented by this $(D DirEntry) is a
symbolic link.
On Windows, return $(D true) when the file is either a symbolic
link or a junction point.
+/
@property bool isSymlink();
/++
Returns the size of the the file represented by this $(D DirEntry)
in bytes.
+/
@property ulong size();
/++
$(BLUE This function is Windows-Only.)
Returns the creation time of the file represented by this
$(D DirEntry).
+/
@property SysTime timeCreated() const;
/++
Returns the time that the file represented by this $(D DirEntry) was
last accessed.
Note that many file systems do not update the access time for files
(generally for performance reasons), so there's a good chance that
$(D timeLastAccessed) will return the same value as
$(D timeLastModified).
+/
@property SysTime timeLastAccessed();
/++
Returns the time that the file represented by this $(D DirEntry) was
last modified.
+/
@property SysTime timeLastModified();
/++
Returns the attributes of the file represented by this $(D DirEntry).
Note that the file attributes on Windows and Posix systems are
completely different. On, Windows, they're what is returned by
$(D GetFileAttributes)
$(WEB msdn.microsoft.com/en-us/library/aa364944(v=vs.85).aspx, GetFileAttributes)
Whereas, an Posix systems, they're the $(D st_mode) value which is
part of the $(D stat) struct gotten by calling $(D stat).
On Posix systems, if the file represented by this $(D DirEntry) is a
symbolic link, then attributes are the attributes of the file
pointed to by the symbolic link.
+/
@property uint attributes();
/++
On Posix systems, if the file represented by this $(D DirEntry) is a
symbolic link, then $(D linkAttributes) are the attributes of the
symbolic link itself. Otherwise, $(D linkAttributes) is identical to
$(D attributes).
On Windows, $(D linkAttributes) is identical to $(D attributes). It
exists on Windows so that you don't have to special-case code for
Windows when dealing with symbolic links.
+/
@property uint linkAttributes();
version(Windows)
alias void* stat_t;
/++
$(BLUE This function is Posix-Only.)
The $(D stat) struct gotten from calling $(D stat).
+/
@property stat_t statBuf();
}
}
else version(Windows)
{
struct DirEntry
{
public:
alias name this;
this(string path)
{
if(!path.exists)
throw new FileException(path, "File does not exist");
_name = path;
with (getFileAttributesWin(path))
{
_size = makeUlong(nFileSizeLow, nFileSizeHigh);
_timeCreated = std.datetime.FILETIMEToSysTime(&ftCreationTime);
_timeLastAccessed = std.datetime.FILETIMEToSysTime(&ftLastAccessTime);
_timeLastModified = std.datetime.FILETIMEToSysTime(&ftLastWriteTime);
_attributes = dwFileAttributes;
}
}
private this(string path, in WIN32_FIND_DATA* fd)
{
auto clength = to!int(core.stdc.string.strlen(fd.cFileName.ptr));
// Convert cFileName[] to unicode
const wlength = MultiByteToWideChar(0, 0, fd.cFileName.ptr, clength, null, 0);
auto wbuf = new wchar[wlength];
const n = MultiByteToWideChar(0, 0, fd.cFileName.ptr, clength, wbuf.ptr, wlength);
assert(n == wlength);
// toUTF8() returns a new buffer
_name = buildPath(path, std.utf.toUTF8(wbuf[0 .. wlength]));
_size = (cast(ulong)fd.nFileSizeHigh << 32) | fd.nFileSizeLow;
_timeCreated = std.datetime.FILETIMEToSysTime(&fd.ftCreationTime);
_timeLastAccessed = std.datetime.FILETIMEToSysTime(&fd.ftLastAccessTime);
_timeLastModified = std.datetime.FILETIMEToSysTime(&fd.ftLastWriteTime);
_attributes = fd.dwFileAttributes;
}
private this(string path, in WIN32_FIND_DATAW *fd)
{
size_t clength = std.string.wcslen(fd.cFileName.ptr);
_name = std.utf.toUTF8(fd.cFileName[0 .. clength]);
_name = buildPath(path, std.utf.toUTF8(fd.cFileName[0 .. clength]));
_size = (cast(ulong)fd.nFileSizeHigh << 32) | fd.nFileSizeLow;
_timeCreated = std.datetime.FILETIMEToSysTime(&fd.ftCreationTime);
_timeLastAccessed = std.datetime.FILETIMEToSysTime(&fd.ftLastAccessTime);
_timeLastModified = std.datetime.FILETIMEToSysTime(&fd.ftLastWriteTime);
_attributes = fd.dwFileAttributes;
}
@property string name() const pure nothrow
{
return _name;
}
@property bool isDir() const pure nothrow
{
return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
@property bool isFile() const pure nothrow
{
//Are there no options in Windows other than directory and file?
//If there are, then this probably isn't the best way to determine
//whether this DirEntry is a file or not.
return !isDir;
}
@property bool isSymlink() const pure nothrow
{
return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
}
@property ulong size() const pure nothrow
{
return _size;
}
@property SysTime timeCreated() const pure nothrow
{
return cast(SysTime)_timeCreated;
}
@property SysTime timeLastAccessed() const pure nothrow
{
return cast(SysTime)_timeLastAccessed;
}
@property SysTime timeLastModified() const pure nothrow
{
return cast(SysTime)_timeLastModified;
}
@property uint attributes() const pure nothrow
{
return _attributes;
}
@property uint linkAttributes() const pure nothrow
{
return _attributes;
}
private:
string _name; /// The file or directory represented by this DirEntry.
SysTime _timeCreated; /// The time when the file was created.
SysTime _timeLastAccessed; /// The time when the file was last accessed.
SysTime _timeLastModified; /// The time when the file was last modified.
ulong _size; /// The size of the file in bytes.
uint _attributes; /// The file attributes from WIN32_FIND_DATAW.
}
}
else version(Posix)
{
struct DirEntry
{
public:
alias name this;
this(string path)
{
if(!path.exists)
throw new FileException(path, "File does not exist");
_name = path;
_didLStat = false;
_didStat = false;
_dTypeSet = false;
}
private this(string path, core.sys.posix.dirent.dirent* fd)
{
immutable len = core.stdc.string.strlen(fd.d_name.ptr);
_name = buildPath(path, fd.d_name[0 .. len]);
_didLStat = false;
_didStat = false;
//fd_d_type doesn't work for all file systems,
//in which case the result is DT_UNKOWN. But we
//can determine the correct type from lstat, so
//we'll only set the dtype here if we could
//correctly determine it (not lstat in the case
//of DT_UNKNOWN in case we don't ever actually
//need the dtype, thus potentially avoiding the
//cost of calling lstat).
if(fd.d_type != DT_UNKNOWN)
{
_dType = fd.d_type;
_dTypeSet = true;
}
else
_dTypeSet = false;
}
@property string name() const pure nothrow
{
return _name;
}
@property bool isDir()
{
_ensureStatDone();
return (_statBuf.st_mode & S_IFMT) == S_IFDIR;
}
@property bool isFile()
{
_ensureStatDone();
return (_statBuf.st_mode & S_IFMT) == S_IFREG;
}
@property bool isSymlink()
{
_ensureLStatDone();
return (_lstatMode & S_IFMT) == S_IFLNK;
}
@property ulong size()
{
_ensureStatDone();
return _statBuf.st_size;
}
@property SysTime timeStatusChanged()
{
_ensureStatDone();
return SysTime(unixTimeToStdTime(_statBuf.st_ctime));
}
@property SysTime timeLastAccessed()
{
_ensureStatDone();
return SysTime(unixTimeToStdTime(_statBuf.st_ctime));
}
@property SysTime timeLastModified()
{
_ensureStatDone();
return SysTime(unixTimeToStdTime(_statBuf.st_mtime));
}
@property uint attributes()
{
_ensureStatDone();
return _statBuf.st_mode;
}
@property uint linkAttributes()
{
_ensureLStatDone();
return _lstatMode;
}
@property stat_t statBuf()
{
_ensureStatDone();
return _statBuf;
}
private:
/++
This is to support lazy evaluation, because doing stat's is
expensive and not always needed.
+/
void _ensureStatDone()
{
if(_didStat)
return;
enforce(stat(toStringz(_name), &_statBuf) == 0,
"Failed to stat file `" ~ _name ~ "'");
_didStat = true;
}
/++
This is to support lazy evaluation, because doing stat's is
expensive and not always needed.
+/
void _ensureLStatDone()
{
if(_didLStat)
return;
stat_t statbuf = void;
enforce(lstat(toStringz(_name), &statbuf) == 0,
"Failed to stat file `" ~ _name ~ "'");
_lstatMode = statbuf.st_mode;
_dTypeSet = true;
_didLStat = true;
}
string _name; /// The file or directory represented by this DirEntry.
stat_t _statBuf = void; /// The result of stat().
uint _lstatMode; /// The stat mode from lstat().
ubyte _dType; /// The type of the file.
bool _didLStat = false; /// Whether lstat() has been called for this DirEntry.
bool _didStat = false; /// Whether stat() has been called for this DirEntry.
bool _dTypeSet = false; /// Whether the dType of the file has been set.
}
}
unittest
{
version(Windows)
{
if("C:\\Program Files\\".exists)
{
auto de = DirEntry("C:\\Program Files\\");
assert(!de.isFile);
assert(de.isDir);
assert(!de.isSymlink);
}
if("C:\\Users\\".exists && "C:\\Documents and Settings\\".exists)
{
auto de = DirEntry("C:\\Documents and Settings\\");
assert(de.isSymlink);
}
if("C:\\Windows\\system.ini".exists)
{
auto de = DirEntry("C:\\Windows\\system.ini");
assert(de.isFile);
assert(!de.isDir);
assert(!de.isSymlink);
}
}
else version(Posix)
{
if("/usr/include".exists)
{
{
auto de = DirEntry("/usr/include");
assert(!de.isFile);
assert(de.isDir);
assert(!de.isSymlink);
}
immutable symfile = deleteme ~ "_slink\0";
scope(exit) if(symfile.exists) symfile.remove();
core.sys.posix.unistd.symlink("/usr/include", symfile.ptr);
{
auto de = DirEntry(symfile);
assert(!de.isFile);
assert(de.isDir);
assert(de.isSymlink);
}
}
if("/usr/include/assert.h".exists)
{
auto de = DirEntry("/usr/include/assert.h");
assert(de.isFile);
assert(!de.isDir);
assert(!de.isSymlink);
}
}
}
/***************************************************
Copy file $(D from) to file $(D to). File timestamps are preserved.
If the target file exists, it is overwritten.
Throws: $(D FileException) on error.
*/
void copy(in char[] from, in char[] to)
{
version(Windows)
{
immutable result = CopyFileW(std.utf.toUTF16z(from), std.utf.toUTF16z(to), false);
if (!result)
throw new FileException(to.idup);
}
else version(Posix)
{
immutable fd = core.sys.posix.fcntl.open(toStringz(from), O_RDONLY);
cenforce(fd != -1, from);
scope(exit) core.sys.posix.unistd.close(fd);
stat_t statbuf = void;
cenforce(fstat(fd, &statbuf) == 0, from);
//cenforce(core.sys.posix.sys.stat.fstat(fd, &statbuf) == 0, from);
auto toz = toStringz(to);
immutable fdw = core.sys.posix.fcntl.open(toz,
O_CREAT | O_WRONLY | O_TRUNC, octal!666);
cenforce(fdw != -1, from);
scope(failure) core.stdc.stdio.remove(toz);
{
scope(failure) core.sys.posix.unistd.close(fdw);
auto BUFSIZ = 4096u * 16;
auto buf = core.stdc.stdlib.malloc(BUFSIZ);
if (!buf)
{
BUFSIZ = 4096;
buf = core.stdc.stdlib.malloc(BUFSIZ);
buf || assert(false, "Out of memory in std.file.copy");
}
scope(exit) core.stdc.stdlib.free(buf);
for (auto size = statbuf.st_size; size; )
{
immutable toxfer = (size > BUFSIZ) ? BUFSIZ : cast(size_t) size;
cenforce(
core.sys.posix.unistd.read(fd, buf, toxfer) == toxfer
&& core.sys.posix.unistd.write(fdw, buf, toxfer) == toxfer,
from);
assert(size >= toxfer);
size -= toxfer;
}
}
cenforce(core.sys.posix.unistd.close(fdw) != -1, from);
utimbuf utim = void;
utim.actime = cast(time_t)statbuf.st_atime;
utim.modtime = cast(time_t)statbuf.st_mtime;
cenforce(utime(toz, &utim) != -1, from);
}
}
unittest
{
auto t1 = deleteme, t2 = deleteme~"2";
scope(exit) foreach (t; [t1, t2]) if (t.exists) t.remove();
write(t1, "1");
copy(t1, t2);
assert(readText(t2) == "1");
write(t1, "2");
copy(t1, t2);
assert(readText(t2) == "2");
}
/++
Remove directory and all of its content and subdirectories,
recursively.
Throws:
$(D FileException) if there is an error (including if the given
file is not a directory).
+/
void rmdirRecurse(in char[] pathname)
{
//No references to pathname will be kept after rmdirRecurse,
//so the cast is safe
rmdirRecurse(DirEntry(cast(string)pathname));
}
/++
Remove directory and all of its content and subdirectories,
recursively.
Throws:
$(D FileException) if there is an error (including if the given
file is not a directory).
+/
void rmdirRecurse(ref DirEntry de)
{
if(!de.isDir)
throw new FileException(de.name, "Not a directory");
if(de.isSymlink)
remove(de.name);
else
{
// all children, recursively depth-first
foreach(DirEntry e; dirEntries(de.name, SpanMode.depth, false))
{
attrIsDir(e.linkAttributes) ? rmdir(e.name) : remove(e.name);
}
// the dir itself
rmdir(de.name);
}
}
///ditto
//Note, without this overload, passing an RValue DirEntry still works, but
//actually fully reconstructs a DirEntry inside the
//"rmdirRecurse(in char[] pathname)" implementation. That is needlessly
//expensive.
//A DirEntry is a bit big (72B), so keeping the "by ref" signature is desirable.
void rmdirRecurse(DirEntry de)
{
rmdirRecurse(de);
}
version(Windows) unittest
{
auto d = deleteme ~ r".dir\a\b\c\d\e\f\g";
mkdirRecurse(d);
rmdirRecurse(deleteme ~ ".dir");
enforce(!exists(deleteme ~ ".dir"));
}
version(Posix) unittest
{
collectException(rmdirRecurse(deleteme));
auto d = deleteme~"/a/b/c/d/e/f/g";
enforce(collectException(mkdir(d)));
mkdirRecurse(d);
core.sys.posix.unistd.symlink((deleteme~"/a/b/c\0").ptr,
(deleteme~"/link\0").ptr);
rmdirRecurse(deleteme~"/link");
enforce(exists(d));
rmdirRecurse(deleteme);
enforce(!exists(deleteme));
d = deleteme~"/a/b/c/d/e/f/g";
mkdirRecurse(d);
std.process.system("ln -sf "~deleteme~"/a/b/c "~deleteme~"/link");
rmdirRecurse(deleteme);
enforce(!exists(deleteme));
}
unittest
{
void[] buf;
buf = new void[10];
(cast(byte[])buf)[] = 3;
if (exists("unittest_write.tmp")) remove("unittest_write.tmp");
write("unittest_write.tmp", buf);
void buf2[] = read("unittest_write.tmp");
assert(buf == buf2);
copy("unittest_write.tmp", "unittest_write2.tmp");
buf2 = read("unittest_write2.tmp");
assert(buf == buf2);
remove("unittest_write.tmp");
assert(!exists("unittest_write.tmp"));
remove("unittest_write2.tmp");
assert(!exists("unittest_write2.tmp"));
}
/**
* Dictates directory spanning policy for $(D_PARAM dirEntries) (see below).
*/
enum SpanMode
{
/** Only spans one directory. */
shallow,
/** Spans the directory depth-first, i.e. the content of any
subdirectory is spanned before that subdirectory itself. Useful
e.g. when recursively deleting files. */
depth,
/** Spans the directory breadth-first, i.e. the content of any
subdirectory is spanned right after that subdirectory itself. */
breadth,
}
private struct DirIteratorImpl
{
SpanMode _mode;
// Whether we should follow symlinked directories while iterating.
// It also indicates whether we should avoid functions which call
// stat (since we should only need lstat in this case and it would
// be more efficient to not call stat in addition to lstat).
bool _followSymlink;
DirEntry _cur;
Appender!(DirHandle[]) _stack;
Appender!(DirEntry[]) _stashed; //used in depth first mode
//stack helpers
void pushExtra(DirEntry de){ _stashed.put(de); }
//ditto
bool hasExtra(){ return !_stashed.data.empty; }
//ditto
DirEntry popExtra()
{
DirEntry de;
de = _stashed.data[$-1];
_stashed.shrinkTo(_stashed.data.length - 1);
return de;
}
version(Windows)
{
struct DirHandle
{
string dirpath;
HANDLE h;
}
bool stepIn(string directory)
{
string search_pattern = buildPath(directory, "*.*");
WIN32_FIND_DATAW findinfo;
HANDLE h = FindFirstFileW(toUTF16z(search_pattern), &findinfo);
cenforce(h != INVALID_HANDLE_VALUE, directory);
_stack.put(DirHandle(directory, h));
return toNext(false, &findinfo);
}
bool next()
{
if(_stack.data.empty)
return false;
WIN32_FIND_DATAW findinfo;
return toNext(true, &findinfo);
}
bool toNext(bool fetch, WIN32_FIND_DATAW* findinfo)
{
if(fetch)
{
if(FindNextFileW(_stack.data[$-1].h, findinfo) == FALSE)
{
popDirStack();
return false;
}
}
while( std.string.wcscmp(findinfo.cFileName.ptr, ".") == 0
|| std.string.wcscmp(findinfo.cFileName.ptr, "..") == 0)
if(FindNextFileW(_stack.data[$-1].h, findinfo) == FALSE)
{
popDirStack();
return false;
}
_cur = DirEntry(_stack.data[$-1].dirpath, findinfo);
return true;
}
bool toNext(bool fetch, WIN32_FIND_DATA* findinfo)
{
if(fetch)
{
if(FindNextFileA(_stack.data[$-1].h, findinfo) == FALSE)
{
popDirStack();
return false;
}
}
while( core.stdc.string.strcmp(findinfo.cFileName.ptr, ".") == 0
|| core.stdc.string.strcmp(findinfo.cFileName.ptr, "..") == 0)
if(FindNextFileA(_stack.data[$-1].h, findinfo) == FALSE)
{
popDirStack();
return false;
}
_cur = DirEntry(_stack.data[$-1].dirpath, findinfo);
return true;
}
void popDirStack()
{
assert(!_stack.data.empty);
FindClose(_stack.data[$-1].h);
_stack.shrinkTo(_stack.data.length-1);
}
void releaseDirStack()
{
foreach( d; _stack.data)
FindClose(d.h);
}
bool mayStepIn()
{
return _followSymlink ? _cur.isDir : _cur.isDir && !_cur.isSymlink;
}
}
else version(Posix)
{
struct DirHandle
{
string dirpath;
DIR* h;
}
bool stepIn(string directory)
{
auto h = cenforce(opendir(toStringz(directory)), directory);
_stack.put(DirHandle(directory, h));
return next();
}
bool next()
{
if(_stack.data.empty)
return false;
for(dirent* fdata; (fdata = readdir(_stack.data[$-1].h)) != null; )
{
// Skip "." and ".."
if(core.stdc.string.strcmp(fdata.d_name.ptr, ".") &&
core.stdc.string.strcmp(fdata.d_name.ptr, "..") )
{
_cur = DirEntry(_stack.data[$-1].dirpath, fdata);
return true;
}
}
popDirStack();
return false;
}
void popDirStack()
{
assert(!_stack.data.empty);
closedir(_stack.data[$-1].h);
_stack.shrinkTo(_stack.data.length-1);
}
void releaseDirStack()
{
foreach( d; _stack.data)
closedir(d.h);
}
bool mayStepIn()
{
return _followSymlink ? _cur.isDir : attrIsDir(_cur.linkAttributes);
}
}
this(string pathname, SpanMode mode, bool followSymlink)
{
_mode = mode;
_followSymlink = followSymlink;
_stack = appender(cast(DirHandle[])[]);
if(_mode == SpanMode.depth)
_stashed = appender(cast(DirEntry[])[]);
if(stepIn(pathname))
{
if(_mode == SpanMode.depth)
while(mayStepIn())
{
auto thisDir = _cur;
if(stepIn(_cur.name))
{
pushExtra(thisDir);
}
else
break;
}
}
}
@property bool empty(){ return _stashed.data.empty && _stack.data.empty; }
@property DirEntry front(){ return _cur; }
void popFront()
{
switch(_mode)
{
case SpanMode.depth:
if(next())
{
while(mayStepIn())
{
auto thisDir = _cur;
if(stepIn(_cur.name))
{
pushExtra(thisDir);
}
else
break;
}
}
else if(hasExtra())
_cur = popExtra();
break;
case SpanMode.breadth:
if(mayStepIn())
{
if(!stepIn(_cur.name))
while(!empty && !next()){}
}
else
while(!empty && !next()){}
break;
default:
next();
}
}
~this()
{
releaseDirStack();
}
}
struct DirIterator
{
private:
RefCounted!(DirIteratorImpl, RefCountedAutoInitialize.no) impl;
this(string pathname, SpanMode mode, bool followSymlink)
{
impl = typeof(impl)(pathname, mode, followSymlink);
}
public:
@property bool empty(){ return impl.empty; }
@property DirEntry front(){ return impl.front; }
void popFront(){ impl.popFront(); }
}
/++
Returns an input range of DirEntry that lazily iterates a given directory,
also provides two ways of foreach iteration. The iteration variable can be of
type $(D_PARAM string) if only the name is needed, or $(D_PARAM DirEntry)
if additional details are needed. The span mode dictates the how the
directory is traversed. The name of the each directory entry iterated
contains the absolute path.
Params:
path = The directory to iterate over.
mode = Whether the directory's sub-directories should be iterated
over depth-first ($(D_PARAM depth)), breadth-first
($(D_PARAM breadth)), or not at all ($(D_PARAM shallow)).
followSymlink = Whether symbolic links which point to directories
should be treated as directories and their contents
iterated over.
Throws:
$(D FileException) if the directory does not exist.
Examples:
--------------------
// Iterate a directory in depth
foreach (string name; dirEntries("destroy/me", SpanMode.depth))
{
remove(name);
}
// Iterate a directory in breadth
foreach (string name; dirEntries(".", SpanMode.breadth))
{
writeln(name);
}
// Iterate a directory and get detailed info about it
foreach (DirEntry e; dirEntries("dmd-testing", SpanMode.breadth))
{
writeln(e.name, "\t", e.size);
}
// Iterate over all *.d files in current directory and all its subdirectories
auto dFiles = filter!`endsWith(a.name,".d")`(dirEntries(".",SpanMode.depth));
foreach(d; dFiles)
writeln(d.name);
// Hook it up with std.parallelism to compile them all in parallel:
foreach(d; parallel(dFiles, 1)) //passes by 1 file to each thread
{
string cmd = "dmd -c " ~ d.name;
writeln(cmd);
std.process.system(cmd);
}
--------------------
+/
auto dirEntries(string path, SpanMode mode, bool followSymlink = true)
{
return DirIterator(path, mode, followSymlink);
}
unittest
{
string testdir = "deleteme.dmd.unittest.std.file" ~ to!string(getpid()); // needs to be relative
mkdirRecurse(buildPath(testdir, "somedir"));
scope(exit) rmdirRecurse(testdir);
write(buildPath(testdir, "somefile"), null);
write(buildPath(testdir, "somedir", "somedeepfile"), null);
// testing range interface
size_t equalEntries(string relpath, SpanMode mode)
{
auto len = enforce(walkLength(dirEntries(absolutePath(relpath), mode)));
assert(walkLength(dirEntries(relpath, mode)) == len);
assert(equal(
map!(a => std.path.absolutePath(a.name))(dirEntries(relpath, mode)),
map!(a => a.name)(dirEntries(absolutePath(relpath), mode))));
return len;
}
assert(equalEntries(testdir, SpanMode.shallow) == 2);
assert(equalEntries(testdir, SpanMode.depth) == 3);
assert(equalEntries(testdir, SpanMode.breadth) == 3);
// testing opApply
foreach (string name; dirEntries(testdir, SpanMode.breadth))
{
//writeln(name);
assert(name.startsWith(testdir));
}
foreach (DirEntry e; dirEntries(absolutePath(testdir), SpanMode.breadth))
{
//writeln(name);
assert(e.isFile || e.isDir, e.name);
}
}
unittest
{
//issue 7264
foreach (string name; dirEntries(".", "*.d", SpanMode.breadth))
{
}
foreach (entry; dirEntries(".", SpanMode.breadth))
{
static assert(is(typeof(entry) == DirEntry));
}
//issue 7138
auto a = array(dirEntries(".", SpanMode.shallow));
// issue 11392
auto dFiles = dirEntries(".", SpanMode.shallow);
foreach(d; dFiles){}
}
/++
Convenience wrapper for filtering file names with a glob pattern.
Params:
path = The directory to iterate over.
pattern = String with wildcards, such as $(RED "*.d"). The supported
wildcard strings are described under
$(XREF path, globMatch).
mode = Whether the directory's sub-directories should be iterated
over depth-first ($(D_PARAM depth)), breadth-first
($(D_PARAM breadth)), or not at all ($(D_PARAM shallow)).
followSymlink = Whether symbolic links which point to directories
should be treated as directories and their contents
iterated over.
Throws:
$(D FileException) if the directory does not exist.
Examples:
--------------------
// Iterate over all D source files in current directory and all its
// subdirectories
auto dFiles = dirEntries(".","*.{d,di}",SpanMode.depth);
foreach(d; dFiles)
writeln(d.name);
--------------------
+/
auto dirEntries(string path, string pattern, SpanMode mode,
bool followSymlink = true)
{
bool f(DirEntry de) { return globMatch(baseName(de.name), pattern); }
return filter!f(DirIterator(path, mode, followSymlink));
}
/++
$(RED Deprecated. It will be removed in July 2014.
Please use $(LREF DirEntry) constructor directly instead.)
Returns a DirEntry for the given file (or directory).
Params:
name = The file (or directory) to get a DirEntry for.
Throws:
$(D FileException) if the file does not exist.
+/
deprecated("Please use DirEntry constructor directly instead.")
DirEntry dirEntry(in char[] name)
{
return DirEntry(name.idup);
}
//Test dirEntry with a directory.
unittest
{
auto before = Clock.currTime();
Thread.sleep(dur!"seconds"(2));
immutable path = deleteme ~ "_dir";
scope(exit) { if(path.exists) rmdirRecurse(path); }
mkdir(path);
Thread.sleep(dur!"seconds"(2));
auto de = dirEntry(path);
assert(de.name == path);
assert(de.isDir);
assert(!de.isFile);
assert(!de.isSymlink);
assert(de.isDir == path.isDir);
assert(de.isFile == path.isFile);
assert(de.isSymlink == path.isSymlink);
assert(de.size == path.getSize());
assert(de.attributes == getAttributes(path));
assert(de.linkAttributes == getLinkAttributes(path));
auto now = Clock.currTime();
scope(failure) writefln("[%s] [%s] [%s] [%s]", before, de.timeLastAccessed, de.timeLastModified, now);
assert(de.timeLastAccessed > before);
assert(de.timeLastAccessed < now);
assert(de.timeLastModified > before);
assert(de.timeLastModified < now);
assert(attrIsDir(de.attributes));
assert(attrIsDir(de.linkAttributes));
assert(!attrIsFile(de.attributes));
assert(!attrIsFile(de.linkAttributes));
assert(!attrIsSymlink(de.attributes));
assert(!attrIsSymlink(de.linkAttributes));
version(Windows)
{
assert(de.timeCreated > before);
assert(de.timeCreated < now);
}
else version(Posix)
{
assert(de.timeStatusChanged > before);
assert(de.timeStatusChanged < now);
assert(de.attributes == de.statBuf.st_mode);
}
}
//Test dirEntry with a file.
unittest
{
auto before = Clock.currTime();
Thread.sleep(dur!"seconds"(2));
immutable path = deleteme ~ "_file";
scope(exit) { if(path.exists) remove(path); }
write(path, "hello world");
Thread.sleep(dur!"seconds"(2));
auto de = dirEntry(path);
assert(de.name == path);
assert(!de.isDir);
assert(de.isFile);
assert(!de.isSymlink);
assert(de.isDir == path.isDir);
assert(de.isFile == path.isFile);
assert(de.isSymlink == path.isSymlink);
assert(de.size == path.getSize());
assert(de.attributes == getAttributes(path));
assert(de.linkAttributes == getLinkAttributes(path));
auto now = Clock.currTime();
scope(failure) writefln("[%s] [%s] [%s] [%s]", before, de.timeLastAccessed, de.timeLastModified, now);
assert(de.timeLastAccessed > before);
assert(de.timeLastAccessed < now);
assert(de.timeLastModified > before);
assert(de.timeLastModified < now);
assert(!attrIsDir(de.attributes));
assert(!attrIsDir(de.linkAttributes));
assert(attrIsFile(de.attributes));
assert(attrIsFile(de.linkAttributes));
assert(!attrIsSymlink(de.attributes));
assert(!attrIsSymlink(de.linkAttributes));
version(Windows)
{
assert(de.timeCreated > before);
assert(de.timeCreated < now);
}
else version(Posix)
{
assert(de.timeStatusChanged > before);
assert(de.timeStatusChanged < now);
assert(de.attributes == de.statBuf.st_mode);
}
}
//Test dirEntry with a symlink to a directory.
version(linux) unittest
{
auto before = Clock.currTime();
Thread.sleep(dur!"seconds"(2));
immutable orig = deleteme ~ "_dir";
mkdir(orig);
immutable path = deleteme ~ "_slink";
scope(exit) { if(orig.exists) rmdirRecurse(orig); }
scope(exit) { if(path.exists) remove(path); }
core.sys.posix.unistd.symlink((orig ~ "\0").ptr, (path ~ "\0").ptr);
Thread.sleep(dur!"seconds"(2));
auto de = dirEntry(path);
assert(de.name == path);
assert(de.isDir);
assert(!de.isFile);
assert(de.isSymlink);
assert(de.isDir == path.isDir);
assert(de.isFile == path.isFile);
assert(de.isSymlink == path.isSymlink);
assert(de.size == path.getSize());
assert(de.attributes == getAttributes(path));
assert(de.linkAttributes == getLinkAttributes(path));
auto now = Clock.currTime();
scope(failure) writefln("[%s] [%s] [%s] [%s]", before, de.timeLastAccessed, de.timeLastModified, now);
assert(de.timeLastAccessed > before);
assert(de.timeLastAccessed < now);
assert(de.timeLastModified > before);
assert(de.timeLastModified < now);
assert(attrIsDir(de.attributes));
assert(!attrIsDir(de.linkAttributes));
assert(!attrIsFile(de.attributes));
assert(!attrIsFile(de.linkAttributes));
assert(!attrIsSymlink(de.attributes));
assert(attrIsSymlink(de.linkAttributes));
assert(de.timeStatusChanged > before);
assert(de.timeStatusChanged < now);
assert(de.attributes == de.statBuf.st_mode);
}
//Test dirEntry with a symlink to a file.
version(linux) unittest
{
auto before = Clock.currTime();
Thread.sleep(dur!"seconds"(2));
immutable orig = deleteme ~ "_file";
write(orig, "hello world");
immutable path = deleteme ~ "_slink";
scope(exit) { if(orig.exists) remove(orig); }
scope(exit) { if(path.exists) remove(path); }
core.sys.posix.unistd.symlink((orig ~ "\0").ptr, (path ~ "\0").ptr);
Thread.sleep(dur!"seconds"(2));
auto de = dirEntry(path);
assert(de.name == path);
assert(!de.isDir);
assert(de.isFile);
assert(de.isSymlink);
assert(de.isDir == path.isDir);
assert(de.isFile == path.isFile);
assert(de.isSymlink == path.isSymlink);
assert(de.size == path.getSize());
assert(de.attributes == getAttributes(path));
assert(de.linkAttributes == getLinkAttributes(path));
auto now = Clock.currTime();
scope(failure) writefln("[%s] [%s] [%s] [%s]", before, de.timeLastAccessed, de.timeLastModified, now);
assert(de.timeLastAccessed > before);
assert(de.timeLastAccessed < now);
assert(de.timeLastModified > before);
assert(de.timeLastModified < now);
assert(!attrIsDir(de.attributes));
assert(!attrIsDir(de.linkAttributes));
assert(attrIsFile(de.attributes));
assert(!attrIsFile(de.linkAttributes));
assert(!attrIsSymlink(de.attributes));
assert(attrIsSymlink(de.linkAttributes));
assert(de.timeStatusChanged > before);
assert(de.timeStatusChanged < now);
assert(de.attributes == de.statBuf.st_mode);
}
/**
Reads an entire file into an array.
Example:
----
// Load file; each line is an int followed by comma, whitespace and a
// double.
auto a = slurp!(int, double)("filename", "%s, %s");
----
*/
Select!(Types.length == 1, Types[0][], Tuple!(Types)[])
slurp(Types...)(string filename, in char[] format)
{
typeof(return) result;
auto app = appender!(typeof(return))();
ElementType!(typeof(return)) toAdd;
auto f = File(filename);
scope(exit) f.close();
foreach (line; f.byLine())
{
formattedRead(line, format, &toAdd);
enforce(line.empty,
text("Trailing characters at the end of line: `", line,
"'"));
app.put(toAdd);
}
return app.data;
}
unittest
{
// Tuple!(int, double)[] x;
// auto app = appender(&x);
write(deleteme, "12 12.25\n345 1.125");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
auto a = slurp!(int, double)(deleteme, "%s %s");
assert(a.length == 2);
assert(a[0] == tuple(12, 12.25));
assert(a[1] == tuple(345, 1.125));
}
/**
Returns the path to a directory for temporary files.
On Windows, this function returns the result of calling the Windows API function
$(LINK2 http://msdn.microsoft.com/en-us/library/windows/desktop/aa364992.aspx, $(D GetTempPath)).
On POSIX platforms, it searches through the following list of directories
and returns the first one which is found to exist:
$(OL
$(LI The directory given by the $(D TMPDIR) environment variable.)
$(LI The directory given by the $(D TEMP) environment variable.)
$(LI The directory given by the $(D TMP) environment variable.)
$(LI $(D /tmp))
$(LI $(D /var/tmp))
$(LI $(D /usr/tmp))
)
On all platforms, $(D tempDir) returns $(D ".") on failure, representing
the current working directory.
The return value of the function is cached, so the procedures described
above will only be performed the first time the function is called. All
subsequent runs will return the same string, regardless of whether
environment variables and directory structures have changed in the
meantime.
The POSIX $(D tempDir) algorithm is inspired by Python's
$(LINK2 http://docs.python.org/library/tempfile.html#tempfile.tempdir, $(D tempfile.tempdir)).
*/
string tempDir() @trusted
{
static string cache;
if (cache is null)
{
version(Windows)
{
wchar[MAX_PATH] buf;
DWORD len = GetTempPathW(buf.length, buf.ptr);
if (len) cache = toUTF8(buf[0 .. len]);
}
else version(Posix)
{
// This function looks through the list of alternative directories
// and returns the first one which exists and is a directory.
static string findExistingDir(T...)(lazy T alternatives)
{
foreach (dir; alternatives)
if (!dir.empty && exists(dir)) return dir;
return null;
}
cache = findExistingDir(environment.get("TMPDIR"),
environment.get("TEMP"),
environment.get("TMP"),
"/tmp",
"/var/tmp",
"/usr/tmp");
}
else static assert (false, "Unsupported platform");
if (cache is null) cache = ".";
}
return cache;
}
|