This file is indexed.

/usr/include/d2/4.6/std/file.d is in libphobos2-4.6-dev 0.29.1-4.6.3-1ubuntu1.

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
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
// 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 $(D $(LINK2 std_stdio.html,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;

import std.metastrings; //For generating deprecation messages only. Remove once
                        //deprecation path complete.

version (Win32)
{
    import core.sys.windows.windows, std.windows.charset,
        std.windows.syserror, std.__fileinit : useWfuncs;
/*
 * Since Win 9x does not support the "W" API's, first convert
 * to wchar, then convert to multibyte using the current code
 * page.
 * (Thanks to yaneurao for this)
 */
    version(Windows) alias std.windows.charset.toMBSz toMBSz;
}
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 : Thread;

    private string deleteme()
    {
        static _deleteme = "deleteme.dmd.unittest";
        static _first = true;

        if(_first)
        {
            version(Windows)
                _deleteme = buildPath(std.process.getenv("TEMP"), _deleteme);
            else version(Posix)
                _deleteme = "/tmp/" ~ _deleteme;

            _first = false;
        }


        return _deleteme;
    }
}


// @@@@ TEMPORARY - THIS SHOULD BE IN THE CORE @@@
// {{{
version (Posix)
{
    version (OSX)
    {
        struct struct_stat64        // distinguish it from the stat() function
        {
            uint st_dev;        /// device
            ushort st_mode;
            ushort st_nlink;        /// link count
            ulong st_ino;        /// file serial number
            uint st_uid;        /// user ID of file's owner
            uint st_gid;        /// user ID of group's owner
            uint st_rdev;        /// if device then device number

            int st_atime;
            uint st_atimensec;
            int st_mtime;
            uint st_mtimensec;
            int st_ctime;
            uint st_ctimensec;
            int st_birthtime;
            uint st_birthtimensec;

            ulong st_size;
            long st_blocks;        /// number of allocated 512 byte blocks
            int st_blksize;        /// optimal I/O block size

            ulong st_ino64;
            uint st_flags;
            uint st_gen;
            int st_lspare; /* RESERVED: DO NOT USE! */
            long st_qspare[2]; /* RESERVED: DO NOT USE! */
        }

        extern(C) int fstat64(int, struct_stat64*);
        extern(C) int stat64(in char*, struct_stat64*);
        extern(C) int lstat64(in char*, struct_stat64*);
    }
    else version (FreeBSD)
    {
        alias core.sys.posix.sys.stat.stat_t struct_stat64;
        alias core.sys.posix.sys.stat.fstat  fstat64;
        alias core.sys.posix.sys.stat.stat   stat64;
        alias core.sys.posix.sys.stat.lstat  lstat64;
    }
    else
    {
        version(X86)
        {
            struct struct_stat64        // distinguish it from the stat() function
            {
                ulong st_dev;        /// device
                uint __pad1;
                uint st_ino;        /// file serial number
                uint st_mode;        /// file mode
                uint st_nlink;        /// link count
                uint st_uid;        /// user ID of file's owner
                uint st_gid;        /// user ID of group's owner
                ulong st_rdev;        /// if device then device number
                uint __pad2;
                align(4) ulong st_size;
                int st_blksize;        /// optimal I/O block size
                ulong st_blocks;        /// number of allocated 512 byte blocks
                int st_atime;
                uint st_atimensec;
                int st_mtime;
                uint st_mtimensec;
                int st_ctime;
                uint st_ctimensec;

                ulong st_ino64;
            }
            //static assert(struct_stat64.sizeof == 88); // copied from d1, but it's currently 96 bytes, not 88.
        }
        else version (X86_64)
        {
            struct struct_stat64
            {
                ulong st_dev;
                ulong st_ino;
                ulong st_nlink;
                uint  st_mode;
                uint  st_uid;
                uint  st_gid;
                int   __pad0;
                ulong st_rdev;
                long  st_size;
                long  st_blksize;
                long  st_blocks;
                long  st_atime;
                ulong st_atimensec;
                long  st_mtime;
                ulong st_mtimensec;
                long  st_ctime;
                ulong st_ctimensec;
                long[3]  __unused;
            }
            static assert(struct_stat64.sizeof == 144);
        }

        extern(C) int fstat64(int, struct_stat64*);
        extern(C) int stat64(in char*, struct_stat64*);
        extern(C) int lstat64(in char*, 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__)
    {
        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 getErrno) in Posix).

        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.
     +/
    version(Windows) this(in char[] name,
                          uint errno = GetLastError,
                          string file = __FILE__,
                          size_t line = __LINE__)
    {
        this(name, sysErrorString(errno), file, line);
        this.errno = errno;
    }

    /++
        Constructor which takes the error number ($(LUCKY GetLastError)
        in Windows, $(D_PARAM getErrno) in Posix).

        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.
     +/
    version(Posix) this(in char[] name,
                        uint errno = .getErrno,
                        string file = __FILE__,
                        size_t line = __LINE__)
    {
        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, .getErrno(), 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 = useWfuncs
            ? CreateFileW(std.utf.toUTF16z(name), defaults)
            : CreateFileA(toMBSz(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);

        struct_stat64 statbuf = void;
        cenforce(fstat64(fd, &statbuf) == 0, name);
        //cenforce(core.sys.posix.sys.stat.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 = useWfuncs
            ? CreateFileW(std.utf.toUTF16z(name), defaults)
            : CreateFileA(toMBSz(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 = useWfuncs
            ? CreateFileW(std.utf.toUTF16z(name), defaults)
            : CreateFileA(toMBSz(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).
 * Throws: $(D FileException) on error.
 */
void rename(in char[] from, in char[] to)
{
    version(Windows)
    {
        enforce(useWfuncs
                ? MoveFileW(std.utf.toUTF16z(from), std.utf.toUTF16z(to))
                : MoveFileA(toMBSz(from), toMBSz(to)),
                new FileException(
                    text("Attempting to rename file ", from, " to ",
                            to)));
    }
    else version(Posix)
        cenforce(std.c.stdio.rename(toStringz(from), toStringz(to)) == 0, to);
}

/***************************************************
Delete file $(D name).
Throws: $(D FileException) on error.
 */
void remove(in char[] name)
{
    version(Windows)
    {
        cenforce(useWfuncs
                ? DeleteFileW(std.utf.toUTF16z(name))
                : DeleteFileA(toMBSz(name)),
                name);
    }
    else version(Posix)
        cenforce(std.c.stdio.remove(toStringz(name)) == 0,
            "Failed to remove file " ~ name);
}

/***************************************************
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)
    {
        HANDLE findhndl = void;
        uint resulth = void;
        uint resultl = void;
        const (char)[] file = name[];

        //FindFirstFileX can't handle file names which end in a backslash.
        if(file.endsWith(sep))
            file.popBackN(sep.length);

        if (useWfuncs)
        {
            WIN32_FIND_DATAW filefindbuf;

            findhndl = FindFirstFileW(std.utf.toUTF16z(file), &filefindbuf);
            resulth = filefindbuf.nFileSizeHigh;
            resultl = filefindbuf.nFileSizeLow;
        }
        else
        {
            WIN32_FIND_DATA filefindbuf;

            findhndl = FindFirstFileA(toMBSz(file), &filefindbuf);
            resulth = filefindbuf.nFileSizeHigh;
            resultl = filefindbuf.nFileSizeLow;
        }

        cenforce(findhndl != cast(HANDLE)-1 && FindClose(findhndl), file);
        return (cast(ulong) resulth << 32) + resultl;
    }
    else version(Posix)
    {
        struct_stat64 statbuf = void;
        cenforce(stat64(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);
}

/*************************
 * $(RED Deprecated. It will be removed in February 2012. Please use either the
 *       version of $(D getTimes) which takes two arguments or $(D getTimesWin)
 *       (Windows-Only) instead.)
 */
version(StdDdoc) deprecated void getTimes(in char[] name,
                                          out d_time ftc,
                                          out d_time fta,
                                          out d_time ftm);
else version(Windows) deprecated void getTimes(C)(in C[] name,
                                                  out d_time ftc,
                                                  out d_time fta,
                                                  out d_time ftm) if(is(Unqual!C == char))
{
    pragma(msg, "Notice: As of Phobos 2.055, the version of std.file.getTimes " ~
                "with 3 arguments has been deprecated. It will be removed in " ~
                "February 2012. Please use either the version of getTimes with " ~
                "two arguments or getTimesWin (Windows-Only) instead.");

    HANDLE findhndl = void;

    if (useWfuncs)
    {
        WIN32_FIND_DATAW filefindbuf;

        findhndl = FindFirstFileW(std.utf.toUTF16z(name), &filefindbuf);
        ftc = FILETIME2d_time(&filefindbuf.ftCreationTime);
        fta = FILETIME2d_time(&filefindbuf.ftLastAccessTime);
        ftm = FILETIME2d_time(&filefindbuf.ftLastWriteTime);
    }
    else
    {
        WIN32_FIND_DATA filefindbuf;

        findhndl = FindFirstFileA(toMBSz(name), &filefindbuf);
        ftc = FILETIME2d_time(&filefindbuf.ftCreationTime);
        fta = FILETIME2d_time(&filefindbuf.ftLastAccessTime);
        ftm = FILETIME2d_time(&filefindbuf.ftLastWriteTime);
    }

    if (findhndl == cast(HANDLE)-1)
    {
        throw new FileException(name.idup);
    }
    FindClose(findhndl);
}
else version(Posix) deprecated void getTimes(C)(in C[] name,
                                                out d_time ftc,
                                                out d_time fta,
                                                out d_time ftm) if(is(Unqual!C == char))
{
    pragma(msg, "Notice: As of Phobos 2.055, the version of std.file.getTimes " ~
                "with 3 arguments has been deprecated. It will be removed in " ~
                "February 2012. Please use either the version of getTimes with " ~
                "two arguments or getTimesWin (Windows-Only) instead.");

    struct_stat64 statbuf = void;
    cenforce(stat64(toStringz(name), &statbuf) == 0, name);
    ftc = cast(d_time) statbuf.st_ctime * ticksPerSecond;
    fta = cast(d_time) statbuf.st_atime * ticksPerSecond;
    ftm = cast(d_time) statbuf.st_mtime * ticksPerSecond;
}


/++
    Get the access and modified times of file $(D name).

    Params:
        name                 = File name to get times for.
        fileAccessTime       = Time the file was last accessed.
        fileModificationTime = Time the file was last modified.

    Throws:
        $(D FileException) on error.
 +/
version(StdDdoc) void getTimes(in char[] name,
                               out SysTime fileAccessTime,
                               out SysTime fileModificationTime);
//Oh, how it would be nice of you could overload templated functions with
//non-templated functions. Untemplatize this when the old getTimes goes away.
else void getTimes(C)(in C[] name,
                      out SysTime fileAccessTime,
                      out SysTime fileModificationTime)
    if(is(Unqual!C == char))
{
    version(Windows)
    {
        HANDLE findhndl = void;

        if(useWfuncs)
        {
            WIN32_FIND_DATAW filefindbuf;

            findhndl = FindFirstFileW(std.utf.toUTF16z(name), &filefindbuf);
            fileAccessTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftLastAccessTime);
            fileModificationTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftLastWriteTime);
        }
        else
        {
            WIN32_FIND_DATA filefindbuf;

            findhndl = FindFirstFileA(toMBSz(name), &filefindbuf);
            fileAccessTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftLastAccessTime);
            fileModificationTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftLastWriteTime);
        }

        enforce(findhndl != cast(HANDLE)-1, new FileException(name.idup));

        FindClose(findhndl);
    }
    else version(Posix)
    {
        struct_stat64 statbuf = void;

        cenforce(stat64(toStringz(name), &statbuf) == 0, name);

        fileAccessTime = SysTime(unixTimeToStdTime(statbuf.st_atime));
        fileModificationTime = 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"(2);

    {
        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);
    }

    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)
{
    HANDLE findhndl = void;

    if (useWfuncs)
    {
        WIN32_FIND_DATAW filefindbuf;

        findhndl = FindFirstFileW(std.utf.toUTF16z(name), &filefindbuf);
        fileCreationTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftCreationTime);
        fileAccessTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftLastAccessTime);
        fileModificationTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftLastWriteTime);
    }
    else
    {
        WIN32_FIND_DATA filefindbuf;

        findhndl = FindFirstFileA(toMBSz(name), &filefindbuf);
        fileCreationTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftCreationTime);
        fileAccessTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftLastAccessTime);
        fileModificationTime = std.datetime.FILETIMEToSysTime(&filefindbuf.ftLastWriteTime);
    }

    if(findhndl == cast(HANDLE)-1)
    {
        throw new FileException(name.idup);
    }

    FindClose(findhndl);
}

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"(3);

    {
        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);
        }

        assert(abs(diffc) <= leeway);
        assert(abs(diffa) <= leeway);
        assert(abs(diffm) <= leeway);
    }

    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);
}

/++
    $(RED Scheduled for deprecation in November 2011. Please use the
          $(D getTimes) with two arguments instead.)

    $(BLUE This function is Posix-Only.)

    Get file status change time, acces time, and modification times
    of file $(D name).

    $(D getTimes) is the same on both Windows and Posix, but it is not
    possible to get the file creation time on Posix systems, so
    $(D getTimes) cannot give you the file creation time. $(D getTimesWin)
    does the same thing on Windows as $(D getTimes) except that it also gives
    you the file creation time. This function was created to do the same
    thing that the old, 3 argument $(D getTimes) was doing on Posix - giving
    you the time that the file status last changed - but ultimately, that's
    not really very useful, and we don't like having functions which are
    OS-specific when we can reasonably avoid it. So, this function is being
    deprecated. You can use $(D DirEntry)'s  $(D statBuf) property if you
    really want to get at that information (along with all of the other
    OS-specific stuff that $(D stat) gives you).

    Params:
        name                 = File name to get times for.
        fileStatusChangeTime = Time the file's status was last changed.
        fileAccessTime       = Time the file was last accessed.
        fileModificationTime = Time the file was last modified.

    Throws:
        $(D FileException) on error.
 +/
version(StdDdoc) void getTimesPosix(in char[] name,
                                    out SysTime fileStatusChangeTime,
                                    out SysTime fileAccessTime,
                                    out SysTime fileModificationTime);
else version(Posix) void getTimesPosix(C)(in C[] name,
                                          out SysTime fileStatusChangeTime,
                                          out SysTime fileAccessTime,
                                          out SysTime fileModificationTime)
    if(is(Unqual!C == char))
{
    pragma(msg, "Notice: As of Phobos 2.054, std.file.getTimesPosix has been " ~
                "scheduled for deprecation in November 2011. Please use " ~
                "the version of getTimes with two arguments instead.");

    struct_stat64 statbuf = void;

    cenforce(stat64(toStringz(name), &statbuf) == 0, name);

    fileStatusChangeTime = SysTime(unixTimeToStdTime(statbuf.st_ctime));
    fileAccessTime = SysTime(unixTimeToStdTime(statbuf.st_atime));
    fileModificationTime = SysTime(unixTimeToStdTime(statbuf.st_mtime));
}


/++
 $(RED Deprecated. It will be removed in February 2012. Please use
       $(D timeLastModified) instead.)
 +/
version(StdDdoc) deprecated d_time lastModified(in char[] name);
else deprecated d_time lastModified(C)(in C[] name)
    if(is(Unqual!C == char))
{
    pragma(msg, hardDeprec!("2.055", "February 2012", "lastModified", "timeLastModified"));

    version(Windows)
    {
        d_time dummy = void, ftm = void;
        getTimes(name, dummy, dummy, ftm);
        return ftm;
    }
    else version(Posix)
    {
        struct_stat64 statbuf = void;
        cenforce(stat64(toStringz(name), &statbuf) == 0, name);
        return cast(d_time) statbuf.st_mtime * ticksPerSecond;
    }
}


/++
 $(RED Deprecated. It will be removed in February 2012. Please use
       $(D timeLastModified) instead.)
 +/
version(StdDdoc) deprecated d_time lastModified(in char[] name, d_time returnIfMissing);
else deprecated d_time lastModified(C)(in C[] name, d_time returnIfMissing)
    if(is(Unqual!C == char))
{
    pragma(msg, hardDeprec!("2.055", "February 2012", "lastModified", "timeLastModified"));

    version(Windows)
    {
        if (!exists(name)) return returnIfMissing;
        d_time dummy = void, ftm = void;
        getTimes(name, dummy, dummy, ftm);
        return ftm;
    }
    else version(Posix)
    {
        struct_stat64 statbuf = void;
        return stat64(toStringz(name), &statbuf) != 0
            ? returnIfMissing
            : cast(d_time) statbuf.st_mtime * ticksPerSecond;
    }
}

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", d_time.min));
    //assert(lastModified("deleteme") > lastModified(__FILE__));
}

/++
    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)
    {
        struct_stat64 statbuf = void;

        cenforce(stat64(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)
    {
        struct_stat64 statbuf = void;

        return stat64(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.
 +/
@property bool exists(in char[] name)
{
    version(Windows)
    {
        auto result = useWfuncs
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/
// fileio/base/getfileattributes.asp
            ? GetFileAttributesW(std.utf.toUTF16z(name))
            : GetFileAttributesA(toMBSz(name));
        return result != 0xFFFFFFFF;
    }
    else version(Posix)
    {
        return access(toStringz(name), 0) == 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.
  +/
uint getAttributes(in char[] name)
{
    version(Windows)
    {
        auto result = useWfuncs ?
                      GetFileAttributesW(std.utf.toUTF16z(name)) :
                      GetFileAttributesA(toMBSz(name));

        enforce(result != uint.max, new FileException(name.idup));

        return result;
    }
    else version(Posix)
    {
        struct_stat64 statbuf = void;

        cenforce(stat64(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)
    {
        struct_stat64 lstatbuf = void;
        cenforce(lstat64(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);
    }
}

/++
 $(RED Deprecated. It will be removed in February 2012. Please use
       $(D isDir) instead.)
 +/
deprecated alias isDir isdir;


/++
    $(RED Scheduled for deprecation in November 2011.
          Please use $(D attrIsDir) instead.)

    Returns whether the given file attributes are for a directory.

    Params:
        attributes = The file attributes.
  +/
@property bool isDir(uint attributes) nothrow
{
    version(Windows)
    {
        return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
    }
    else version(Posix)
    {
        return (attributes & S_IFMT) == S_IFDIR;
    }
}


/++
    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);
    }
}

/++
 $(RED Deprecated. It will be removed in February 2012. Please use
       $(D isDir) instead.)
 +/
deprecated alias isFile isfile;


/++
    $(RED Scheduled for deprecation in November 2011.
          Please use $(D attrIsFile) instead.)

    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 isFile) or $(D isDir) will return $(D 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). 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.
  +/
@property bool isFile(uint attributes) nothrow
{
    version(Windows)
    {
        return (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
    }
    else version(Posix)
    {
        return (attributes & S_IFMT) == S_IFREG;
    }
}


/++
    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.

    Always return false on Windows. It exists on Windows so that you don't
    have to special-case code for Windows when dealing with symbolic links.

    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 false;
    else version(Posix)
        return (getLinkAttributes(name) & S_IFMT) == S_IFLNK;
}

unittest
{
    version(Windows)
    {
        if("C:\\Program Files\\".exists)
            assert(!"C:\\Program Files\\".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(isFile(getAttributes(fakeSymFile)));
            assert(isFile(getLinkAttributes(fakeSymFile)));
            assert(!isDir(getAttributes(fakeSymFile)));
            assert(!isDir(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(isDir(getAttributes(symfile)));
            assert(!isDir(getLinkAttributes(symfile)));

            assert(!isFile(getAttributes(symfile)));
            assert(!isFile(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(!isDir(getAttributes(symfile)));
            assert(!isDir(getLinkAttributes(symfile)));

            assert(isFile(getAttributes(symfile)));
            assert(!isFile(getLinkAttributes(symfile)));
        }
    }
}


/++
    $(RED Scheduled for deprecation in November 2011.
          Please use $(D attrIsSymlink) instead.)

    Returns whether the given file attributes are for a symbolic link.

    Always return $(D false) on Windows. It exists on Windows so that you don't
    have to special-case code for Windows when dealing with symbolic links.

    Params:
        attributes = The file attributes.
  +/
@property bool isSymLink(uint attributes) nothrow
{
    version(Windows)
        return false;
    else version(Posix)
        return (attributes & S_IFMT) == S_IFLNK;
}


/++
    Returns whether the given file attributes are for a symbolic link.

    Always return $(D false) on Windows. It exists on Windows so that you don't
    have to special-case code for Windows when dealing with symbolic links.

    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 false;
    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(useWfuncs
                ? SetCurrentDirectoryW(std.utf.toUTF16z(pathname))
                : SetCurrentDirectoryA(toMBSz(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(useWfuncs
                ? CreateDirectoryW(std.utf.toUTF16z(pathname), null)
                : CreateDirectoryA(toMBSz(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.
 */

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(useWfuncs
                ? RemoveDirectoryW(std.utf.toUTF16z(pathname))
                : RemoveDirectoryA(toMBSz(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.

    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(isDir(getAttributes(symfile)));
        assert(!isDir(getLinkAttributes(symfile)));

        assert(!isFile(getAttributes(symfile)));
        assert(!isFile(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(!isDir(getAttributes(symfile)));
        assert(!isDir(getLinkAttributes(symfile)));

        assert(isFile(getAttributes(symfile)));
        assert(!isFile(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)
{
    char[2048] buffer;
    immutable size = cenforce(core.sys.posix.unistd.readlink(toUTFz!(const char*)(link),
                                                             buffer,
                                                             buffer.length),
                              link);

    return to!string(buffer[0 .. (size >= buffer.length ? $ - 1 : size)]);
}

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();
            scope(failure) std.stdio.stderr.writefln("Failed file: %s", file);

            symlink(file, symfile);

            assert(readLink(symfile) == file);
        }
    }
}

/****************************************************
 * 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.
    */
    ushort[4096] staticBuff = void; //enough for most common case
    if (useWfuncs)
    {
        auto buffW = cast(wchar[]) staticBuff;
        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
    {
        auto buffA = cast(char[]) staticBuff;
        immutable n = cenforce(GetCurrentDirectoryA(to!DWORD(buffA.length), buffA.ptr),
                "getcwd");
        // fromMBSz doesn't always produce a fresh string
        if(n < buffA.length)
        {
            string res = fromMBSz(cast(immutable)buffA.ptr);
            return res.ptr == buffA.ptr ? res.idup : res;
        }
        else //staticBuff isn't enough
        {
            auto ptr = cast(char*) malloc(char.sizeof * n);
            scope(exit) free(ptr);
            immutable n2 = GetCurrentDirectoryA(n, ptr);
            cenforce(n2 && n2 < n, "getcwd");

            string res = fromMBSz(cast(immutable)ptr);
            return res.ptr == ptr ? res.idup : res;
        }
    }
}

version (Posix) string getcwd()
{
    auto p = cenforce(core.sys.posix.unistd.getcwd(null, 0),
            "cannot get cwd");
    scope(exit) std.c.stdlib.free(p);
    return p[0 .. std.c.string.strlen(p)].idup;
}

unittest
{
    auto s = getcwd();
    assert(s.length);
}


version(StdDdoc)
{
    /++
        Info on a file, similar to what you'd get from stat on a Posix system.

        A $(D DirEntry) is obtained by using the functions $(D dirEntry) (to get
        the $(D DirEntry) for a specific file) or $(D dirEntries) (to get a
        $(D DirEntry) for each file/directory in a particular directory).
      +/
    struct DirEntry
    {
        void _init(T...)(T);
    public:

        /++
            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();

        /++
         $(RED Deprecated. It will be removed in February 2012. Please use
               $(D isDir) instead.)
         +/
        deprecated alias isDir 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();

        /++
         $(RED Deprecated. It will be removed in February 2012. Please use
               $(D isFile) instead.)
         +/
        deprecated alias isFile isfile;

        /++
            Returns whether the file represented by this $(D DirEntry) is a
            symbolic link.

            Always return false on Windows. It exists on Windows so that you don't
            have to special-case code for Windows when dealing with symbolic links.
          +/
        @property bool isSymlink();

        /++
            Returns the size of the the file represented by this $(D DirEntry)
            in bytes.
          +/
        @property ulong size();

        /++
            $(RED Deprecated. It will be removed in February 2012. Please use
                   $(D timeCreated) instead.)

            Returns the creation time of the file represented by this
            $(D DirEntry).

            $(RED Note that this property has existed for both Windows and Posix
                  systems but that it is $(I incorrect) on Posix systems. Posix
                  systems do not have access to the creation time of a file. On
                  Posix systems this property has incorrectly been the time that
                  the file's status status last changed. If you want that value,
                  then get it from the $(D statBuf) property, which gives you
                  access to the $(D stat) struct which Posix systems use (check
                  out $(D stat)'s man page for more details.))
          +/
        deprecated @property d_time creationTime() const;

        /++
            $(BLUE This function is Windows-Only.)

            Returns the creation time of the file represented by this
            $(D DirEntry).
          +/
        @property SysTime timeCreated() const;


        /++
            $(RED Scheduled for deprecation in November 2011. It will not be
                  replaced. You can use $(D attributes) to get at this
                  information if you need it.)

            $(BLUE This function is Posix-Only.)

            Returns the last time that the status of file represented by this
            $(D DirEntry) was changed (i.e. owner, group, link count, mode, etc.).
          +/
        @property SysTime timeStatusChanged();

        /++
            $(RED Deprecated. It will be removed in February 2012. Please use
                  $(D timeLastAccessed) instead.)

            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 lastAccessTime) will return the same value as $(D lastWriteTime).
          +/
        deprecated @property d_time lastAccessTime();

        /++
            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();

        /++
            $(RED Deprecated. It will be removed in February 2012. Please use
                  $(D timeLastModified) instead.)

            Returns the time that the file represented by this $(D DirEntry) was
            last modified.
          +/
        deprecated @property d_time lastWriteTime();

        /++
            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* struct_stat64;

        /++
            $(BLUE This function is Posix-Only.)

            The $(D stat) struct gotten from calling $(D stat).
          +/
        @property struct_stat64 statBuf();
    }
}
else version(Windows)
{
    struct DirEntry
    {
    public:

        @property string name() const
        {
            return _name;
        }

        @property bool isDir() const
        {
            return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
        }

        deprecated alias isDir isdir;

        @property bool isFile() const
        {
            //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;
        }

        deprecated alias isFile isfile;

        @property bool isSymlink() const
        {
            return false;
        }

        @property ulong size() const
        {
            return _size;
        }

        deprecated @property d_time creationTime() const
        {
            return sysTimeToDTime(_timeCreated);
        }

        @property SysTime timeCreated() const
        {
            return cast(SysTime)_timeCreated;
        }

        deprecated @property d_time lastAccessTime() const
        {
            return sysTimeToDTime(_timeLastAccessed);
        }

        @property SysTime timeLastAccessed() const
        {
            return cast(SysTime)_timeLastAccessed;
        }

        deprecated @property d_time lastWriteTime() const
        {
            return sysTimeToDTime(_timeLastModified);
        }

        @property SysTime timeLastModified() const
        {
            return cast(SysTime)_timeLastModified;
        }

        @property uint attributes() const
        {
            return _attributes;
        }

        @property uint linkAttributes() const
        {
            return _attributes;
        }

    private:

        void _init(in char[] path)
        {
            HANDLE findhndl = void;
            uint resulth = void;
            uint resultl = void;
            _name = path.idup;

            //FindFirstFileX can't handle file names which end in a backslash.
            if(_name.endsWith(sep))
                _name.popBackN(sep.length);

            if(useWfuncs)
            {
                WIN32_FIND_DATAW fd;

                findhndl = FindFirstFileW(std.utf.toUTF16z(_name), &fd);
                enforce(findhndl != INVALID_HANDLE_VALUE);

                _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;
            }
            else
            {
                WIN32_FIND_DATA fd;

                findhndl = FindFirstFileA(toMBSz(_name), &fd);
                enforce(findhndl != INVALID_HANDLE_VALUE);

                _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;
            }

            cenforce(findhndl != cast(HANDLE)-1 && FindClose(findhndl), _name);
        }

        void _init(in char[] path, in WIN32_FIND_DATA* fd)
        {
            auto clength = to!int(std.c.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;
        }

        void _init(in char[] 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;
        }


        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:

        @property string name() const
        {
            return _name;
        }

        @property bool isDir()
        {
            _ensureStatDone();

            return (_statBuf.st_mode & S_IFMT) == S_IFDIR;
        }

        deprecated alias isDir isdir;

        @property bool isFile()
        {
            _ensureStatDone();

            return (_statBuf.st_mode & S_IFMT) == S_IFREG;
        }

        deprecated alias isFile isfile;

        @property bool isSymlink()
        {
            _ensureLStatDone();

            return (_lstatMode & S_IFMT) == S_IFLNK;
        }

        // This property was not documented before, and it's almost
        // worthless, since the odds are high that it will be DT_UNKNOWN,
        // so it continues to be left undocumented.
        //
        // Will be removed in February 2012.
        deprecated @property ubyte d_type()
        {
            return _dType;
        }

        @property ulong size()
        {
            _ensureStatDone();
            return _statBuf.st_size;
        }

        deprecated @property d_time creationTime()
        {
            _ensureStatDone();

            return cast(d_time)_statBuf.st_ctime * ticksPerSecond;
        }

        @property SysTime timeStatusChanged()
        {
            _ensureStatDone();

            return SysTime(unixTimeToStdTime(_statBuf.st_ctime));
        }

        deprecated @property d_time lastAccessTime()
        {
            _ensureStatDone();

            return cast(d_time)_statBuf.st_atime * ticksPerSecond;
        }

        @property SysTime timeLastAccessed()
        {
            _ensureStatDone();

            return SysTime(unixTimeToStdTime(_statBuf.st_ctime));
        }

        deprecated @property d_time lastWriteTime()
        {
            _ensureStatDone();

            return cast(d_time)_statBuf.st_mtime * ticksPerSecond;
        }

        @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 struct_stat64 statBuf()
        {
            _ensureStatDone();

            return _statBuf;
        }

    private:

        void _init(in char[] path)
        {
            _name = path.idup;

            _didLStat = false;
            _didStat = false;
            _dTypeSet = false;
        }

        void _init(in char[] path, core.sys.posix.dirent.dirent* fd)
        {
            immutable len = std.c.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;
        }

        /++
            This is to support lazy evaluation, because doing stat's is
            expensive and not always needed.
         +/
        void _ensureStatDone()
        {
            if(_didStat)
                return;

            enforce(stat64(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;

            struct_stat64 statbuf = void;

            enforce(lstat64(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.

        struct_stat64 _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:\\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);
        }
    }
}


/******************************************************
 * $(RED Scheduled for deprecation in November 2011. Please use the
 *       $(D getTimes) with two arguments instead.)
 *
 * For each file and directory $(D DirEntry) in $(D pathname[])
 * pass it to the callback delegate.
 *
 * Params:
 *        callback =        Delegate that processes each
 *                        DirEntry in turn. Returns true to
 *                        continue, false to stop.
 * Example:
 *        This program lists all the files in its
 *        path argument and all subdirectories thereof.
 * ----
 * import std.stdio;
 * import std.file;
 *
 * void main(string[] args)
 * {
 *    bool callback(DirEntry* de)
 *    {
 *      if(de.isDir)
 *        listdir(de.name, &callback);
 *      else
 *        writefln(de.name);

 *      return true;
 *    }
 *
 *    listdir(args[1], &callback);
 * }
 * ----
 */
alias listDir listdir;


/***************************************************
Copy file $(D from) to file $(D to). File timestamps are preserved.
 */
void copy(in char[] from, in char[] to)
{
    version(Windows)
    {
        immutable result = useWfuncs
            ? CopyFileW(std.utf.toUTF16z(from), std.utf.toUTF16z(to), false)
            : CopyFileA(toMBSz(from), toMBSz(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);

        struct_stat64 statbuf = void;
        cenforce(fstat64(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) std.c.stdio.remove(toz);
        {
            scope(failure) core.sys.posix.unistd.close(fdw);
            auto BUFSIZ = 4096u * 16;
            auto buf = std.c.stdlib.malloc(BUFSIZ);
            if (!buf)
            {
                BUFSIZ = 4096;
                buf = std.c.stdlib.malloc(BUFSIZ);
                buf || assert(false, "Out of memory in std.file.copy");
            }
            scope(exit) std.c.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);
    }
}

    /++
       $(RED Deprecated. It will be removed in February 2012. Please use the
             version which takes a $(XREF datetime, SysTime) instead.)

        Set access/modified times of file $(D name).

        Throws:
            $(D FileException) on error.
     +/
version(StdDdoc) deprecated void setTimes(in char[] name, d_time fta, d_time ftm);
else deprecated void setTimes(C)(in C[] name, d_time fta, d_time ftm)
    if(is(Unqual!C == char))
{
    pragma(msg, "Notice: As of Phobos 2.055, the version of std.file.setTimes " ~
                "which takes std.date.d_time has been deprecated. It will be " ~
                "removed in February 2012. Please use the version which takes " ~
                "std.datetime.SysTime instead.");

    version(Windows)
    {
        const ta = d_time2FILETIME(fta);
        const tm = d_time2FILETIME(ftm);
        alias TypeTuple!(GENERIC_WRITE, 0, null, OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL, HANDLE.init)
            defaults;
        auto h = useWfuncs
            ? CreateFileW(std.utf.toUTF16z(name), defaults)
            : CreateFileA(toMBSz(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].tv_sec = to!int(fta / ticksPerSecond);
        t[0].tv_usec = cast(int)
            (cast(long) ((cast(double) fta / ticksPerSecond)
                    * 1_000_000) % 1_000_000);
        t[1].tv_sec = to!int(ftm / ticksPerSecond);
        t[1].tv_usec = cast(int)
            (cast(long) ((cast(double) ftm / ticksPerSecond)
                    * 1_000_000) % 1_000_000);
        enforce(utimes(toStringz(name), t) == 0);
    }
}


/++
    Set access/modified times of file $(D name).

    Params:
        fileAccessTime       = Time the file was last accessed.
        fileModificationTime = Time the file was last modified.

    Throws:
        $(D FileException) on error.
 +/
version(StdDdoc) void setTimes(in char[] name,
                               SysTime fileAccessTime,
                               SysTime fileModificationTime);
else void setTimes(C)(in C[] name,
                      SysTime fileAccessTime,
                      SysTime fileModificationTime)
    if(is(Unqual!C == char))
{
    version(Windows)
    {
        const ta = SysTimeToFILETIME(fileAccessTime);
        const tm = SysTimeToFILETIME(fileModificationTime);
        alias TypeTuple!(GENERIC_WRITE,
                         0,
                         null,
                         OPEN_EXISTING,
                         FILE_ATTRIBUTE_NORMAL, HANDLE.init)
              defaults;
        auto h = useWfuncs ?
                 CreateFileW(std.utf.toUTF16z(name), defaults) :
                 CreateFileA(toMBSz(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] = fileAccessTime.toTimeVal();
        t[1] = fileModificationTime.toTimeVal();

        enforce(utimes(toStringz(name), t) == 0);
    }
}

/+
unittest
{
    write(deleteme, "a\n");
    scope(exit) { assert(exists(deleteme)); remove(deleteme); }
    SysTime ftc1, fta1, ftm1;
    getTimes(deleteme, ftc1, fta1, ftm1);
    enforce(collectException(setTimes("nonexistent", fta1, ftm1)));
    setTimes(deleteme, fta1 + dur!"seconds"(50), ftm1 + dur!"seconds"(50));
    SysTime ftc2, fta2, ftm2;
    getTimes(deleteme, ftc2, fta2, ftm2);
    assert(fta1 + dur!"seconds(50) == fta2, text(fta1 + dur!"seconds(50), "!=", fta2));
    assert(ftm1 + dur!"seconds(50) == ftm2);
}
+/


/++
    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)
{
    DirEntry de = dirEntry(pathname);

    rmdirRecurse(de);
}


/++
    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(text("File ", de.name, " is not a directory"));

    if(de.isSymlink())
        remove(de.name);
    else
    {
        // all children, recursively depth-first
        foreach(DirEntry e; dirEntries(de.name, SpanMode.depth, false))
        {
            isDir(e.linkAttributes) ? rmdir(e.name) : remove(e.name);
        }

        // the dir itself
        rmdir(de.name);
    }
}

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
{
    auto d = "/tmp/deleteme/a/b/c/d/e/f/g";
    enforce(collectException(mkdir(d)));
    mkdirRecurse(d);
    core.sys.posix.unistd.symlink("/tmp/deleteme/a/b/c", "/tmp/deleteme/link");
    rmdirRecurse("/tmp/deleteme/link");
    enforce(exists(d));
    rmdirRecurse("/tmp/deleteme");
    enforce(!exists("/tmp/deleteme"));

    d = "/tmp/deleteme/a/b/c/d/e/f/g";
    mkdirRecurse(d);
    std.process.system("ln -sf /tmp/deleteme/a/b/c /tmp/deleteme/link");
    rmdirRecurse("/tmp/deleteme");
    enforce(!exists("/tmp/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"));
}

unittest
{
    _listDir(".", delegate bool (DirEntry * de)
    {
        version(Windows)
        {
            auto s = std.string.format("%s : c %s, w %s, a %s",
                                       de.name,
                                       de.timeCreated,
                                       de.timeLastModified,
                                       de.timeLastAccessed);
        }
        else version(Posix)
        {
            auto s = std.string.format("%s : c %s, w %s, a %s",
                                       de.name,
                                       de.timeStatusChanged,
                                       de.timeLastModified,
                                       de.timeLastAccessed);
        }

        return true;
    }
    );
}

/**
 * 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, "*.*");
            if(useWfuncs)
            {
                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);
            }
            else
            {
                WIN32_FIND_DATA findinfo;
                HANDLE h = FindFirstFileA(toMBSz(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;
            bool result;
            if (useWfuncs)
            {
                WIN32_FIND_DATAW findinfo;
                result = toNext(true, &findinfo);

            }
            else
            {
                WIN32_FIND_DATA findinfo;
                result = toNext(true, &findinfo);
            }
            return result;
        }

        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._init(_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( std.c.string.strcmp(findinfo.cFileName.ptr, ".") == 0
                    || std.c.string.strcmp(findinfo.cFileName.ptr, "..") == 0)
                if(FindNextFileA(_stack.data[$-1].h, findinfo) == FALSE)
                {
                    popDirStack();
                    return false;
                }
            _cur._init(_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);
        }

    }
    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(std.c.string.strcmp(fdata.d_name.ptr, ".")  &&
                   std.c.string.strcmp(fdata.d_name.ptr, "..") )
                {
                    _cur._init(_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);
        }
    }

    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(_followSymlink ? _cur.isDir : isDir(_cur.linkAttributes))
                {
                    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(_followSymlink ? _cur.isDir : isDir(_cur.linkAttributes))
                {
                    auto thisDir = _cur;
                    if(stepIn(_cur.name))
                    {
                        pushExtra(thisDir);
                    }
                    else
                        break;
                }
            }
            else if(hasExtra())
                _cur = popExtra();
            break;
        case SpanMode.breadth:
            if(_followSymlink ? _cur.isDir : isDir(_cur.linkAttributes))
            {
                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(); }
    int opApply(int delegate(ref string name) dg)
    {
        foreach(DirEntry v; impl.refCountedPayload)
        {
            string s = v.name;
            if(dg(s))
                return 1;
        }
        return 0;
    }
    int opApply(int delegate(ref DirEntry name) dg)
    {
        foreach(DirEntry v; impl.refCountedPayload)
            if(dg(v))
                return 1;
        return 0;
    }
}
/++
    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. Ignored on Windows.

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 it's 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"; // 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!(q{std.path.absolutePath(a.name)})(dirEntries(relpath, mode)),
                   map!(q{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);
    }
}

/++
    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.
 +/
DirEntry dirEntry(in char[] name)
{
    if(!name.exists)
        throw new FileException(text("File ", name, " does not exist."));

    DirEntry dirEntry;

    dirEntry._init(name);

    return dirEntry;
}

//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(isDir(de.attributes));
    assert(isDir(de.linkAttributes));
    assert(!isFile(de.attributes));
    assert(!isFile(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(!isDir(de.attributes));
    assert(!isDir(de.linkAttributes));
    assert(isFile(de.attributes));
    assert(isFile(de.linkAttributes));
    assert(!isSymLink(de.attributes));
    assert(!isSymLink(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(isDir(de.attributes));
    assert(!isDir(de.linkAttributes));
    assert(!isFile(de.attributes));
    assert(!isFile(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(!isDir(de.attributes));
    assert(!isDir(de.linkAttributes));
    assert(isFile(de.attributes));
    assert(!isFile(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));
}


/++
    $(RED Scheduled for deprecation in November 2011.
          Please use $(D dirEntries) instead.)

    Returns the contents of the given directory.

    The names in the contents do not include the pathname.

    Throws:
        $(D FileException) on error.

Examples:
    This program lists all the files and subdirectories in its
    path argument.
--------------------
import std.stdio;
import std.file;

void main(string[] args)
{
    auto dirs = std.file.listDir(args[1]);

    foreach(d; dirs)
        writefln(d);
}
--------------------
 +/
string[] listDir(C)(in C[] pathname)
{
    pragma(msg, softDeprec!("2.054", "November 2011", "listDir", "dirEntries"));
    auto result = appender!(string[])();

    bool listing(string filename)
    {
        result.put(filename);
        return true; // continue
    }

    _listDir(pathname, &listing);

    return result.data;
}

unittest
{
    assert(listDir(".").length > 0);
}


/++
    $(RED Scheduled for deprecation in November 2011.
          Please use $(D dirEntries) instead.)

    Returns all the files in the directory and its sub-directories
    which match pattern or regular expression r.

    Params:
        pathname = The path of the directory to search.
        pattern  = String with wildcards, such as $(RED "*.d"). The supported
                   wildcard strings are described under fnmatch() in
                   $(LINK2 std_path.html, std.path).
        r        = Regular expression, for more powerful pattern matching.
        followSymlink = Whether symbolic links which point to directories
                         should be treated as directories and their contents
                         iterated over. Ignored on Windows.

Examples:
    This program lists all the files with a "d" extension in
    the path passed as the first argument.
--------------------
import std.stdio;
import std.file;

void main(string[] args)
{
  auto d_source_files = std.file.listDir(args[1], "*.d");

  foreach(d; d_source_files)
      writefln(d);
}
--------------------

    A regular expression version that searches for all files with "d" or
    "obj" extensions:
--------------------
import std.stdio;
import std.file;
import std.regexp;

void main(string[] args)
{
  auto d_source_files = std.file.listDir(args[1], RegExp(r"\.(d|obj)$"));

  foreach(d; d_source_files)
      writefln(d);
}
--------------------
 +/
string[] listDir(C, U)(in C[] pathname, U filter, bool followSymlink = true)
    if(is(C : char) && !is(U: bool delegate(string filename)))
{
    pragma(msg, softDeprec!("2.054", "November 2011", "listDir", "dirEntries"));
    import std.regexp;
    auto result = appender!(string[])();
    bool callback(DirEntry* de)
    {
        if(followSymlink ? de.isDir : isDir(de.linkAttributes))
        {
            _listDir(de.name, &callback);
        }
        else
        {
            static if(is(U : const(C[])))
            {//pattern version
                if(std.path.fnmatch(de.name, filter))
                    result.put(de.name);
            }
            else static if(is(U : RegExp))
            {//RegExp version

                if(filter.test(de.name))
                    result.put(de.name);
            }
            else
                static assert(0,"There is no version of listDir that takes " ~ U.stringof);
        }
        return true; // continue
    }

    _listDir(pathname, &callback);

    return result.data;
}

/******************************************************
 * $(RED Scheduled for deprecation in November 2011.
 *       Please use $(D dirEntries) instead.)
 *
 * For each file and directory name in pathname[],
 * pass it to the callback delegate.
 *
 * Params:
 *        callback =        Delegate that processes each
 *                        filename in turn. Returns true to
 *                        continue, false to stop.
 * Example:
 *        This program lists all the files in its
 *        path argument, including the path.
 * ----
 * import std.stdio;
 * import std.path;
 * import std.file;
 *
 * void main(string[] args)
 * {
 *    auto pathname = args[1];
 *    string[] result;
 *
 *    bool listing(string filename)
 *    {
 *      result ~= buildPath(pathname, filename);
 *      return true; // continue
 *    }
 *
 *    listdir(pathname, &listing);
 *
 *    foreach (name; result)
 *      writefln("%s", name);
 * }
 * ----
 */
void listDir(C, U)(in C[] pathname, U callback)
    if(is(C : char) && is(U: bool delegate(string filename)))
{
    pragma(msg, softDeprec!("2.054", "November 2011", "listDir", "dirEntries"));
    _listDir(pathname, callback);
}


//==============================================================================
// Private Section.
//==============================================================================
private:


void _listDir(in char[] pathname, bool delegate(string filename) callback)
{
    bool listing(DirEntry* de)
    {
        return callback(de.name.baseName);
    }

    _listDir(pathname, &listing);
}


version(Windows)
{
    void _listDir(in char[] pathname, bool delegate(DirEntry* de) callback)
    {
        DirEntry de;
        auto c = buildPath(pathname, "*.*");

        if(useWfuncs)
        {
            WIN32_FIND_DATAW fileinfo;

            auto h = FindFirstFileW(std.utf.toUTF16z(c), &fileinfo);
            if(h == INVALID_HANDLE_VALUE)
                return;

            scope(exit) FindClose(h);

            do
            {
                // Skip "." and ".."
                if(std.string.wcscmp(fileinfo.cFileName.ptr, ".") == 0 ||
                   std.string.wcscmp(fileinfo.cFileName.ptr, "..") == 0)
                {
                    continue;
                }

                de._init(pathname, &fileinfo);

                if(!callback(&de))
                    break;

            } while(FindNextFileW(h, &fileinfo) != FALSE);
        }
        else
        {
            WIN32_FIND_DATA fileinfo;

            auto h = FindFirstFileA(toMBSz(c), &fileinfo);

            if(h == INVALID_HANDLE_VALUE)
                return;

            scope(exit) FindClose(h);

            do
            {
                // Skip "." and ".."
                if(std.c.string.strcmp(fileinfo.cFileName.ptr, ".") == 0 ||
                   std.c.string.strcmp(fileinfo.cFileName.ptr, "..") == 0)
                {
                    continue;
                }

                de._init(pathname, &fileinfo);

                if(!callback(&de))
                    break;

            } while(FindNextFileA(h, &fileinfo) != FALSE);
        }
    }
}
else version(Posix)
{
    void _listDir(in char[] pathname, bool delegate(DirEntry* de) callback)
    {
        auto h = cenforce(opendir(toStringz(pathname)), pathname);
        scope(exit) closedir(h);

        DirEntry de;

        for(dirent* fdata; (fdata = readdir(h)) != null; )
        {
            // Skip "." and ".."
            if(!std.c.string.strcmp(fdata.d_name.ptr, ".") ||
               !std.c.string.strcmp(fdata.d_name.ptr, ".."))
            {
                continue;
            }

            de._init(pathname, fdata);

            if(!callback(&de))
                break;
        }
    }
}


//==============================================================================
// Stuff from std.date so that we don't have to import std.date and end up with
// the "scheduled for deprecation" pragma message from std.date showing up just
// because someone imports std.file.
//
// These will be removed either when the functions in std.file which use them
// are removed.
//==============================================================================
//

deprecated alias long d_time;
deprecated enum d_time d_time_nan = long.min;
deprecated enum ticksPerSecond = 1000;

version(Windows)
{
    deprecated d_time FILETIME2d_time(const FILETIME *ft)
    {
        auto sysTime = FILETIMEToSysTime(ft);

        return sysTimeToDTime(sysTime);
    }
}


template softDeprec(string vers, string date, string oldFunc, string newFunc)
{
    enum softDeprec = Format!("Notice: As of Phobos %s, std.file.%s has been scheduled " ~
                              "for deprecation in %s. Please use std.file.%s instead.",
                              vers, oldFunc, date, newFunc);
}


template hardDeprec(string vers, string date, string oldFunc, string newFunc)
{
    enum hardDeprec = Format!("Notice: As of Phobos %s, std.file.%s has been deprecated " ~
                              "It will be removed in %s. Please use std.file.%s instead.",
                              vers, oldFunc, date, newFunc);
}