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 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963
|
// Written in the D programming language.
/**
$(SCRIPT inhibitQuickIndex = 1;)
$(DIVC quickindex,
$(BOOKTABLE,
$(TR $(TH Category) $(TH Symbols))
$(TR $(TD File handles) $(TD
$(MYREF __popen)
$(MYREF File)
$(MYREF isFileHandle)
$(MYREF openNetwork)
$(MYREF stderr)
$(MYREF stdin)
$(MYREF stdout)
))
$(TR $(TD Reading) $(TD
$(MYREF chunks)
$(MYREF lines)
$(MYREF readf)
$(MYREF readfln)
$(MYREF readln)
))
$(TR $(TD Writing) $(TD
$(MYREF toFile)
$(MYREF write)
$(MYREF writef)
$(MYREF writefln)
$(MYREF writeln)
))
$(TR $(TD Misc) $(TD
$(MYREF KeepTerminator)
$(MYREF LockType)
$(MYREF StdioException)
))
))
Standard I/O functions that extend $(LINK2 https://dlang.org/phobos/core_stdc_stdio.html, core.stdc.stdio). $(B core.stdc.stdio)
is $(D_PARAM public)ally imported when importing $(B std.stdio).
There are three layers of I/O:
$(OL
$(LI The lowest layer is the operating system layer. The two main schemes are Windows and Posix.)
$(LI C's $(TT stdio.h) which unifies the two operating system schemes.)
$(LI $(TT std.stdio), this module, unifies the various $(TT stdio.h) implementations into
a high level package for D programs.)
)
Source: $(PHOBOSSRC std/stdio.d)
Copyright: Copyright The D Language Foundation 2007-.
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP digitalmars.com, Walter Bright),
$(HTTP erdani.org, Andrei Alexandrescu),
Alex Rønne Petersen
Macros:
CSTDIO=$(HTTP cplusplus.com/reference/cstdio/$1/, $1)
*/
module std.stdio;
/*
# Glossary
The three layers have many terms for their data structures and types.
Here we try to bring some sanity to them for the intrepid code spelunker.
## Windows
Handle
A Windows handle is an opaque object of type HANDLE.
The `HANDLE` for standard devices can be retrieved with
Windows `GetStdHandle()`.
## Posix
file descriptor, aka fileno, aka fildes
An int from 0..`FOPEN_MAX`, which is an index into some internal data
structure.
0 is for `stdin`, 1 for `stdout`, 2 for `stderr`.
Negative values usually indicate an error.
## stdio.h
`FILE`
A struct that encapsulates the C library's view of the operating system
files. A `FILE` should only be referred to via a pointer.
`fileno`
A field of `FILE` which is the Posix file descriptor for Posix systems, and
and an index into an array of file `HANDLE`s for Windows.
This array is how Posix behavior is emulated on Windows.
For Digital Mars C, that array is `__osfhnd[]`, and is initialized
at program start by the C runtime library.
In this module, they are typed as `fileno_t`.
`stdin`, `stdout`, `stderr`
Global pointers to `FILE` representing standard input, output, and error streams.
Being global means there are synchronization issues when multiple threads
are doing I/O on the same streams.
## std.stdio
*/
import core.stdc.stddef : wchar_t;
public import core.stdc.stdio;
import std.algorithm.mutation : copy;
import std.meta : allSatisfy;
import std.range : ElementEncodingType, empty, front, isBidirectionalRange,
isInputRange, isSomeFiniteCharInputRange, put;
import std.traits : isSomeChar, isSomeString, Unqual;
import std.typecons : Flag, No, Yes;
/++
If flag `KeepTerminator` is set to `KeepTerminator.yes`, then the delimiter
is included in the strings returned.
+/
alias KeepTerminator = Flag!"keepTerminator";
version (CRuntime_Microsoft)
{
}
else version (MinGW) // LDC
{
version = MINGW_IO;
}
else version (CRuntime_Glibc)
{
}
else version (CRuntime_Bionic)
{
version = GENERIC_IO;
}
else version (CRuntime_Musl)
{
version = GENERIC_IO;
}
else version (CRuntime_UClibc)
{
version = GENERIC_IO;
}
else version (OSX)
{
version = GENERIC_IO;
version = Darwin;
}
else version (iOS)
{
version = GENERIC_IO;
version = Darwin;
}
else version (TVOS)
{
version = GENERIC_IO;
version = Darwin;
}
else version (WatchOS)
{
version = GENERIC_IO;
version = Darwin;
}
else version (FreeBSD)
{
version = GENERIC_IO;
}
else version (NetBSD)
{
version = GENERIC_IO;
}
else version (OpenBSD)
{
version = GENERIC_IO;
}
else version (DragonFlyBSD)
{
version = GENERIC_IO;
}
else version (Solaris)
{
version = GENERIC_IO;
}
else
{
static assert(0, "unsupported operating system");
}
// Character type used for operating system filesystem APIs
version (Windows)
{
private alias FSChar = wchar;
}
else
{
private alias FSChar = char;
}
private alias fileno_t = int; // file descriptor, fildes, fileno
version (Windows)
{
// core.stdc.stdio.fopen expects file names to be
// encoded in CP_ACP on Windows instead of UTF-8.
/+ Waiting for druntime pull 299
+/
extern (C) nothrow @nogc FILE* _wfopen(scope const wchar* filename, scope const wchar* mode);
extern (C) nothrow @nogc FILE* _wfreopen(scope const wchar* filename, scope const wchar* mode, FILE* fp);
import core.sys.windows.basetsd : HANDLE;
}
version (Posix)
{
static import core.sys.posix.stdio; // getdelim, flockfile
}
version (CRuntime_Microsoft)
{
private alias _FPUTC = _fputc_nolock;
private alias _FPUTWC = _fputwc_nolock;
private alias _FGETC = _fgetc_nolock;
private alias _FGETWC = _fgetwc_nolock;
private alias _FLOCK = _lock_file;
private alias _FUNLOCK = _unlock_file;
}
else version (CRuntime_Glibc)
{
private alias _FPUTC = fputc_unlocked;
private alias _FPUTWC = fputwc_unlocked;
private alias _FGETC = fgetc_unlocked;
private alias _FGETWC = fgetwc_unlocked;
private alias _FLOCK = core.sys.posix.stdio.flockfile;
private alias _FUNLOCK = core.sys.posix.stdio.funlockfile;
}
else version (MINGW_IO)
{
extern (C)
{
int setmode(int, int);
}
import core.sync.mutex;
__gshared Mutex lockMutex;
__gshared Mutex[uint] fileLocks;
void flockfile(FILE* fp)
{
Mutex mutex;
if (lockMutex is null)
lockMutex = new Mutex;
lockMutex.lock();
if (fp._file in fileLocks)
{
mutex = fileLocks[fp._file];
}
else
{
mutex = new Mutex();
fileLocks[fp._file] = mutex;
}
mutex.lock();
lockMutex.unlock();
}
void funlockfile(FILE* fp)
{
Mutex mutex;
if (lockMutex is null)
lockMutex = new Mutex;
lockMutex.lock();
if (fp._file in fileLocks)
{
mutex = fileLocks[fp._file];
mutex.unlock();
} else
{ /* Should this be an error */ }
lockMutex.unlock();
}
int fputc_unlocked(int c, _iobuf* fp) { return fputc(c, cast(shared) fp); }
int fputwc_unlocked(int c, _iobuf* fp)
{
return fputwc(cast(wchar_t)c, cast(shared) fp);
}
int fgetc_unlocked(_iobuf* fp) { return fgetc(cast(shared) fp); }
int fgetwc_unlocked(_iobuf* fp) { return fgetwc(cast(shared) fp); }
extern (C)
{
nothrow:
@nogc:
FILE* _fdopen(int, const (char)*);
}
alias fputc_unlocked FPUTC;
alias fputwc_unlocked FPUTWC;
alias fgetc_unlocked FGETC;
alias fgetwc_unlocked FGETWC;
alias flockfile FLOCK;
alias funlockfile FUNLOCK;
alias setmode _setmode;
int _fileno(FILE* f) { return f._file; }
alias _fileno fileno;
enum
{
_O_RDONLY = 0x0000,
_O_APPEND = 0x0008,
_O_TEXT = 0x4000,
_O_BINARY = 0x8000,
}
}
else version (GENERIC_IO)
{
nothrow:
@nogc:
extern (C) private
{
static import core.stdc.wchar_;
pragma(mangle, fputc.mangleof) int _FPUTC(int c, _iobuf* fp);
pragma(mangle, core.stdc.wchar_.fputwc.mangleof) int _FPUTWC(wchar_t c, _iobuf* fp);
pragma(mangle, fgetc.mangleof) int _FGETC(_iobuf* fp);
pragma(mangle, core.stdc.wchar_.fgetwc.mangleof) int _FGETWC(_iobuf* fp);
}
version (Posix)
{
private alias _FLOCK = core.sys.posix.stdio.flockfile;
private alias _FUNLOCK = core.sys.posix.stdio.funlockfile;
}
else
{
static assert(0, "don't know how to lock files on GENERIC_IO");
}
}
else
{
static assert(0, "unsupported C I/O system");
}
private extern (C) @nogc nothrow
{
pragma(mangle, _FPUTC.mangleof) int trustedFPUTC(int ch, _iobuf* h) @trusted;
pragma(mangle, _FPUTWC.mangleof) int trustedFPUTWC(wchar_t ch, _iobuf* h) @trusted;
}
//------------------------------------------------------------------------------
private struct ByRecordImpl(Fields...)
{
private:
import std.typecons : Tuple;
File file;
char[] line;
Tuple!(Fields) current;
string format;
public:
this(File f, string format)
{
assert(f.isOpen);
file = f;
this.format = format;
popFront(); // prime the range
}
/// Range primitive implementations.
@property bool empty()
{
return !file.isOpen;
}
/// Ditto
@property ref Tuple!(Fields) front()
{
return current;
}
/// Ditto
void popFront()
{
import std.conv : text;
import std.exception : enforce;
import std.format.read : formattedRead;
import std.string : chomp;
enforce(file.isOpen, "ByRecord: File must be open");
file.readln(line);
if (!line.length)
{
file.detach();
}
else
{
line = chomp(line);
formattedRead(line, format, ¤t);
enforce(line.empty, text("Leftover characters in record: `",
line, "'"));
}
}
}
template byRecord(Fields...)
{
auto byRecord(File f, string format)
{
return typeof(return)(f, format);
}
}
/**
Encapsulates a `FILE*`. Generally D does not attempt to provide
thin wrappers over equivalent functions in the C standard library, but
manipulating `FILE*` values directly is unsafe and error-prone in
many ways. The `File` type ensures safe manipulation, automatic
file closing, and a lot of convenience.
The underlying `FILE*` handle is maintained in a reference-counted
manner, such that as soon as the last `File` variable bound to a
given `FILE*` goes out of scope, the underlying `FILE*` is
automatically closed.
Example:
----
// test.d
import std.stdio;
void main(string[] args)
{
auto f = File("test.txt", "w"); // open for writing
f.write("Hello");
if (args.length > 1)
{
auto g = f; // now g and f write to the same file
// internal reference count is 2
g.write(", ", args[1]);
// g exits scope, reference count decreases to 1
}
f.writeln("!");
// f exits scope, reference count falls to zero,
// underlying `FILE*` is closed.
}
----
$(CONSOLE
% rdmd test.d Jimmy
% cat test.txt
Hello, Jimmy!
% __
)
*/
struct File
{
import core.atomic : atomicOp, atomicStore, atomicLoad;
import std.range.primitives : ElementEncodingType;
import std.traits : isScalarType, isArray;
enum Orientation { unknown, narrow, wide }
private struct Impl
{
FILE * handle = null; // Is null iff this Impl is closed by another File
shared uint refs = uint.max / 2;
bool isPopened; // true iff the stream has been created by popen()
Orientation orientation;
}
private Impl* _p;
private string _name;
package this(FILE* handle, string name, uint refs = 1, bool isPopened = false) @trusted @nogc nothrow
{
import core.stdc.stdlib : malloc;
assert(!_p);
_p = cast(Impl*) malloc(Impl.sizeof);
if (!_p)
{
import core.exception : onOutOfMemoryError;
onOutOfMemoryError();
}
initImpl(handle, name, refs, isPopened);
}
private void initImpl(FILE* handle, string name, uint refs = 1, bool isPopened = false) @nogc nothrow pure @safe
{
assert(_p);
_p.handle = handle;
atomicStore(_p.refs, refs);
_p.isPopened = isPopened;
_p.orientation = Orientation.unknown;
_name = name;
}
/**
Constructor taking the name of the file to open and the open mode.
Copying one `File` object to another results in the two `File`
objects referring to the same underlying file.
The destructor automatically closes the file as soon as no `File`
object refers to it anymore.
Params:
name = range or string representing the file _name
stdioOpenmode = range or string represting the open mode
(with the same semantics as in the C standard library
$(CSTDIO fopen) function)
Throws: `ErrnoException` if the file could not be opened.
*/
this(string name, scope const(char)[] stdioOpenmode = "rb") @safe
{
import std.conv : text;
import std.exception : errnoEnforce;
this(errnoEnforce(_fopen(name, stdioOpenmode),
text("Cannot open file `", name, "' in mode `",
stdioOpenmode, "'")),
name);
// MSVCRT workaround (https://issues.dlang.org/show_bug.cgi?id=14422)
version (CRuntime_Microsoft)
{
setAppendWin(stdioOpenmode);
}
}
/// ditto
this(R1, R2)(R1 name)
if (isSomeFiniteCharInputRange!R1)
{
import std.conv : to;
this(name.to!string, "rb");
}
/// ditto
this(R1, R2)(R1 name, R2 mode)
if (isSomeFiniteCharInputRange!R1 &&
isSomeFiniteCharInputRange!R2)
{
import std.conv : to;
this(name.to!string, mode.to!string);
}
@safe unittest
{
static import std.file;
import std.utf : byChar;
auto deleteme = testFilename();
auto f = File(deleteme.byChar, "w".byChar);
f.close();
std.file.remove(deleteme);
}
~this() @safe
{
detach();
}
this(this) @safe pure nothrow @nogc
{
if (!_p) return;
assert(atomicLoad(_p.refs));
atomicOp!"+="(_p.refs, 1);
}
/**
Assigns a file to another. The target of the assignment gets detached
from whatever file it was attached to, and attaches itself to the new
file.
*/
ref File opAssign(File rhs) @safe return
{
import std.algorithm.mutation : swap;
swap(this, rhs);
return this;
}
// https://issues.dlang.org/show_bug.cgi?id=20129
@safe unittest
{
File[int] aa;
aa.require(0, File.init);
}
/**
Detaches from the current file (throwing on failure), and then attempts to
_open file `name` with mode `stdioOpenmode`. The mode has the
same semantics as in the C standard library $(CSTDIO fopen) function.
Throws: `ErrnoException` in case of error.
*/
void open(string name, scope const(char)[] stdioOpenmode = "rb") @trusted
{
resetFile(name, stdioOpenmode, false);
}
// https://issues.dlang.org/show_bug.cgi?id=20585
@system unittest
{
File f;
try
f.open("doesn't exist");
catch (Exception _e)
{
}
assert(!f.isOpen);
f.close(); // to check not crash here
}
private void resetFile(string name, scope const(char)[] stdioOpenmode, bool isPopened) @trusted
{
import core.stdc.stdlib : malloc;
import std.exception : enforce;
import std.conv : text;
import std.exception : errnoEnforce;
if (_p !is null)
{
detach();
}
FILE* handle;
version (Posix)
{
if (isPopened)
{
errnoEnforce(handle = _popen(name, stdioOpenmode),
"Cannot run command `"~name~"'");
}
else
{
errnoEnforce(handle = _fopen(name, stdioOpenmode),
text("Cannot open file `", name, "' in mode `",
stdioOpenmode, "'"));
}
}
else
{
assert(isPopened == false);
errnoEnforce(handle = _fopen(name, stdioOpenmode),
text("Cannot open file `", name, "' in mode `",
stdioOpenmode, "'"));
}
_p = cast(Impl*) enforce(malloc(Impl.sizeof), "Out of memory");
initImpl(handle, name, 1, isPopened);
version (CRuntime_Microsoft)
{
setAppendWin(stdioOpenmode);
}
}
private void closeHandles() @trusted
{
assert(_p);
import std.exception : errnoEnforce;
version (Posix)
{
import core.sys.posix.stdio : pclose;
import std.format : format;
if (_p.isPopened)
{
auto res = pclose(_p.handle);
errnoEnforce(res != -1,
"Could not close pipe `"~_name~"'");
_p.handle = null;
return;
}
}
if (_p.handle)
{
auto handle = _p.handle;
_p.handle = null;
// fclose disassociates the FILE* even in case of error (https://issues.dlang.org/show_bug.cgi?id=19751)
errnoEnforce(.fclose(handle) == 0,
"Could not close file `"~_name~"'");
}
}
version (CRuntime_Microsoft)
{
private void setAppendWin(scope const(char)[] stdioOpenmode) @safe
{
bool append, update;
foreach (c; stdioOpenmode)
if (c == 'a')
append = true;
else
if (c == '+')
update = true;
if (append && !update)
seek(size);
}
}
/**
Reuses the `File` object to either open a different file, or change
the file mode. If `name` is `null`, the mode of the currently open
file is changed; otherwise, a new file is opened, reusing the C
`FILE*`. The function has the same semantics as in the C standard
library $(CSTDIO freopen) function.
Note: Calling `reopen` with a `null` `name` is not implemented
in all C runtimes.
Throws: `ErrnoException` in case of error.
*/
void reopen(string name, scope const(char)[] stdioOpenmode = "rb") @trusted
{
import std.conv : text;
import std.exception : enforce, errnoEnforce;
import std.internal.cstring : tempCString;
enforce(isOpen, "Attempting to reopen() an unopened file");
auto namez = (name == null ? _name : name).tempCString!FSChar();
auto modez = stdioOpenmode.tempCString!FSChar();
FILE* fd = _p.handle;
version (Windows)
fd = _wfreopen(namez, modez, fd);
else
fd = freopen(namez, modez, fd);
errnoEnforce(fd, name
? text("Cannot reopen file `", name, "' in mode `", stdioOpenmode, "'")
: text("Cannot reopen file in mode `", stdioOpenmode, "'"));
if (name !is null)
_name = name;
}
@safe unittest // Test changing filename
{
import std.exception : assertThrown, assertNotThrown;
static import std.file;
auto deleteme = testFilename();
std.file.write(deleteme, "foo");
scope(exit) std.file.remove(deleteme);
auto f = File(deleteme);
assert(f.readln() == "foo");
auto deleteme2 = testFilename();
std.file.write(deleteme2, "bar");
scope(exit) std.file.remove(deleteme2);
f.reopen(deleteme2);
assert(f.name == deleteme2);
assert(f.readln() == "bar");
f.close();
}
version (CRuntime_Microsoft) {} else // Not implemented
@safe unittest // Test changing mode
{
import std.exception : assertThrown, assertNotThrown;
static import std.file;
auto deleteme = testFilename();
std.file.write(deleteme, "foo");
scope(exit) std.file.remove(deleteme);
auto f = File(deleteme, "r+");
assert(f.readln() == "foo");
f.reopen(null, "w");
f.write("bar");
f.seek(0);
f.reopen(null, "a");
f.write("baz");
assert(f.name == deleteme);
f.close();
assert(std.file.readText(deleteme) == "barbaz");
}
/**
Detaches from the current file (throwing on failure), and then runs a command
by calling the C standard library function $(HTTP
pubs.opengroup.org/onlinepubs/7908799/xsh/popen.html, popen).
Throws: `ErrnoException` in case of error.
*/
version (Posix) void popen(string command, scope const(char)[] stdioOpenmode = "r") @safe
{
resetFile(command, stdioOpenmode ,true);
}
/**
First calls `detach` (throwing on failure), then attempts to
associate the given file descriptor with the `File`, and sets the file's name to `null`.
The mode must be compatible with the mode of the file descriptor.
Throws: `ErrnoException` in case of error.
Params:
fd = File descriptor to associate with this `File`.
stdioOpenmode = Mode to associate with this File. The mode has the same
semantics as in the POSIX library function $(HTTP
pubs.opengroup.org/onlinepubs/7908799/xsh/fdopen.html, fdopen)
and must be compatible with `fd`.
*/
void fdopen(int fd, scope const(char)[] stdioOpenmode = "rb") @safe
{
fdopen(fd, stdioOpenmode, null);
}
package void fdopen(int fd, scope const(char)[] stdioOpenmode, string name) @trusted
{
import std.exception : errnoEnforce;
import std.internal.cstring : tempCString;
auto modez = stdioOpenmode.tempCString();
detach();
version (CRuntime_Microsoft)
{
auto fp = _fdopen(fd, modez);
errnoEnforce(fp);
}
else version (Posix)
{
import core.sys.posix.stdio : fdopen;
auto fp = fdopen(fd, modez);
errnoEnforce(fp);
}
else
static assert(0, "no fdopen() available");
this = File(fp, name);
}
// Declare a dummy HANDLE to allow generating documentation
// for Windows-only methods.
version (StdDdoc) { version (Windows) {} else alias HANDLE = int; }
/**
First calls `detach` (throwing on failure), and then attempts to
associate the given Windows `HANDLE` with the `File`. The mode must
be compatible with the access attributes of the handle. Windows only.
Throws: `ErrnoException` in case of error.
*/
version (StdDdoc)
void windowsHandleOpen(HANDLE handle, scope const(char)[] stdioOpenmode);
version (Windows)
void windowsHandleOpen(HANDLE handle, scope const(char)[] stdioOpenmode)
{
import core.stdc.stdint : intptr_t;
import std.exception : errnoEnforce;
import std.format : format;
// Create file descriptors from the handles
int mode;
modeLoop:
foreach (c; stdioOpenmode)
switch (c)
{
case 'r': mode |= _O_RDONLY; break;
case '+': mode &=~_O_RDONLY; break;
case 'a': mode |= _O_APPEND; break;
case 'b': mode |= _O_BINARY; break;
case 't': mode |= _O_TEXT; break;
case ',': break modeLoop;
default: break;
}
auto fd = _open_osfhandle(cast(intptr_t) handle, mode);
errnoEnforce(fd >= 0, "Cannot open Windows HANDLE");
fdopen(fd, stdioOpenmode, "HANDLE(%s)".format(handle));
}
/** Returns `true` if the file is opened. */
@property bool isOpen() const @safe pure nothrow
{
return _p !is null && _p.handle;
}
/**
Returns `true` if the file is at end (see $(CSTDIO feof)).
Throws: `Exception` if the file is not opened.
*/
@property bool eof() const @trusted pure
{
import std.exception : enforce;
enforce(_p && _p.handle, "Calling eof() against an unopened file.");
return .feof(cast(FILE*) _p.handle) != 0;
}
/**
Returns the name last used to initialize this `File`, if any.
Some functions that create or initialize the `File` set the name field to `null`.
Examples include $(LREF tmpfile), $(LREF wrapFile), and $(LREF fdopen). See the
documentation of those functions for details.
Returns: The name last used to initialize this this file, or `null` otherwise.
*/
@property string name() const @safe pure nothrow return
{
return _name;
}
/**
If the file is closed or not yet opened, returns `true`. Otherwise, returns
$(CSTDIO ferror) for the file handle.
*/
@property bool error() const @trusted pure nothrow
{
return !isOpen || .ferror(cast(FILE*) _p.handle);
}
@safe unittest
{
// https://issues.dlang.org/show_bug.cgi?id=12349
static import std.file;
auto deleteme = testFilename();
auto f = File(deleteme, "w");
scope(exit) std.file.remove(deleteme);
f.close();
assert(f.error);
}
/**
Detaches from the underlying file. If the sole owner, calls `close`.
Throws: `ErrnoException` on failure if closing the file.
*/
void detach() @trusted
{
import core.stdc.stdlib : free;
if (!_p) return;
scope(exit) _p = null;
if (atomicOp!"-="(_p.refs, 1) == 0)
{
scope(exit) free(_p);
closeHandles();
}
}
@safe unittest
{
static import std.file;
auto deleteme = testFilename();
scope(exit) std.file.remove(deleteme);
auto f = File(deleteme, "w");
{
auto f2 = f;
f2.detach();
}
assert(f._p.refs == 1);
f.close();
}
/**
If the file was closed or not yet opened, succeeds vacuously. Otherwise
closes the file (by calling $(CSTDIO fclose)),
throwing on error. Even if an exception is thrown, afterwards the $(D
File) object is empty. This is different from `detach` in that it
always closes the file; consequently, all other `File` objects
referring to the same handle will see a closed file henceforth.
Throws: `ErrnoException` on error.
*/
void close() @trusted
{
import core.stdc.stdlib : free;
import std.exception : errnoEnforce;
if (!_p) return; // succeed vacuously
scope(exit)
{
if (atomicOp!"-="(_p.refs, 1) == 0)
free(_p);
_p = null; // start a new life
}
if (!_p.handle) return; // Impl is closed by another File
scope(exit) _p.handle = null; // nullify the handle anyway
closeHandles();
}
/**
If the file is closed or not yet opened, succeeds vacuously. Otherwise, returns
$(CSTDIO clearerr) for the file handle.
*/
void clearerr() @safe pure nothrow
{
_p is null || _p.handle is null ||
.clearerr(_p.handle);
}
/**
Flushes the C `FILE` buffers.
Calls $(CSTDIO fflush) for the file handle.
Throws: `Exception` if the file is not opened or if the call to `fflush` fails.
*/
void flush() @trusted
{
import std.exception : enforce, errnoEnforce;
enforce(isOpen, "Attempting to flush() in an unopened file");
errnoEnforce(.fflush(_p.handle) == 0);
}
@safe unittest
{
// https://issues.dlang.org/show_bug.cgi?id=12349
import std.exception : assertThrown;
static import std.file;
auto deleteme = testFilename();
auto f = File(deleteme, "w");
scope(exit) std.file.remove(deleteme);
f.close();
assertThrown(f.flush());
}
/**
Forces any data buffered by the OS to be written to disk.
Call $(LREF flush) before calling this function to flush the C `FILE` buffers first.
This function calls
$(HTTP msdn.microsoft.com/en-us/library/windows/desktop/aa364439%28v=vs.85%29.aspx,
`FlushFileBuffers`) on Windows,
$(HTTP developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/fcntl.2.html,
`F_FULLFSYNC fcntl`) on Darwin and
$(HTTP pubs.opengroup.org/onlinepubs/7908799/xsh/fsync.html,
`fsync`) on POSIX for the file handle.
Throws: `Exception` if the file is not opened or if the OS call fails.
*/
void sync() @trusted
{
import std.exception : enforce;
enforce(isOpen, "Attempting to sync() an unopened file");
version (Windows)
{
import core.sys.windows.winbase : FlushFileBuffers;
wenforce(FlushFileBuffers(windowsHandle), "FlushFileBuffers failed");
}
else version (Darwin)
{
import core.sys.darwin.fcntl : fcntl, F_FULLFSYNC;
import std.exception : errnoEnforce;
errnoEnforce(fcntl(fileno, F_FULLFSYNC, 0) != -1, "fcntl failed");
}
else
{
import core.sys.posix.unistd : fsync;
import std.exception : errnoEnforce;
errnoEnforce(fsync(fileno) == 0, "fsync failed");
}
}
/**
Calls $(CSTDIO fread) for the
file handle. The number of items to read and the size of
each item is inferred from the size and type of the input array, respectively.
Returns: The slice of `buffer` containing the data that was actually read.
This will be shorter than `buffer` if EOF was reached before the buffer
could be filled. If the buffer is empty, it will be returned.
Throws: `ErrnoException` if the file is not opened or the call to `fread` fails.
`rawRead` always reads in binary mode on Windows.
*/
T[] rawRead(T)(T[] buffer)
{
import std.exception : enforce, errnoEnforce;
if (!buffer.length)
return buffer;
enforce(isOpen, "Attempting to read from an unopened file");
version (Windows)
{
immutable fileno_t fd = .fileno(_p.handle);
immutable mode = ._setmode(fd, _O_BINARY);
scope(exit) ._setmode(fd, mode);
}
immutable freadResult = trustedFread(_p.handle, buffer);
assert(freadResult <= buffer.length); // fread return guarantee
if (freadResult != buffer.length) // error or eof
{
errnoEnforce(!error);
return buffer[0 .. freadResult];
}
return buffer;
}
///
@system unittest
{
static import std.file;
auto testFile = std.file.deleteme();
std.file.write(testFile, "\r\n\n\r\n");
scope(exit) std.file.remove(testFile);
auto f = File(testFile, "r");
auto buf = f.rawRead(new char[5]);
f.close();
assert(buf == "\r\n\n\r\n");
}
// https://issues.dlang.org/show_bug.cgi?id=24685
static assert(!__traits(compiles, (File f) @safe { int*[1] bar; f.rawRead(bar[]); }));
// https://issues.dlang.org/show_bug.cgi?id=21729
@system unittest
{
import std.exception : assertThrown;
File f;
ubyte[1] u;
assertThrown(f.rawRead(u));
}
// https://issues.dlang.org/show_bug.cgi?id=21728
@system unittest
{
static if (__traits(compiles, { import std.process : pipe; })) // not available for iOS
{
import std.process : pipe;
import std.exception : assertThrown;
auto p = pipe();
p.readEnd.close;
ubyte[1] u;
assertThrown(p.readEnd.rawRead(u));
}
}
// https://issues.dlang.org/show_bug.cgi?id=13893
@system unittest
{
import std.exception : assertNotThrown;
File f;
ubyte[0] u;
assertNotThrown(f.rawRead(u));
}
/**
Calls $(CSTDIO fwrite) for the file
handle. The number of items to write and the size of each
item is inferred from the size and type of the input array, respectively. An
error is thrown if the buffer could not be written in its entirety.
`rawWrite` always writes in binary mode on Windows.
Throws: `ErrnoException` if the file is not opened or if the call to `fwrite` fails.
*/
void rawWrite(T)(in T[] buffer)
{
import std.conv : text;
import std.exception : errnoEnforce;
version (Windows)
{
immutable fileno_t fd = .fileno(_p.handle);
immutable oldMode = ._setmode(fd, _O_BINARY);
if (oldMode != _O_BINARY)
{
// need to flush the data that was written with the original mode
._setmode(fd, oldMode);
flush(); // before changing translation mode ._setmode(fd, _O_BINARY);
._setmode(fd, _O_BINARY);
}
scope (exit)
{
if (oldMode != _O_BINARY)
{
flush();
._setmode(fd, oldMode);
}
}
}
auto result = trustedFwrite(_p.handle, buffer);
if (result == result.max) result = 0;
errnoEnforce(result == buffer.length,
text("Wrote ", result, " instead of ", buffer.length,
" objects of type ", T.stringof, " to file `",
_name, "'"));
}
///
@system unittest
{
static import std.file;
auto testFile = std.file.deleteme();
auto f = File(testFile, "w");
scope(exit) std.file.remove(testFile);
f.rawWrite("\r\n\n\r\n");
f.close();
assert(std.file.read(testFile) == "\r\n\n\r\n");
}
/**
Calls $(CSTDIO fseek)
for the file handle to move its position indicator.
Params:
offset = Binary files: Number of bytes to offset from origin.$(BR)
Text files: Either zero, or a value returned by $(LREF tell).
origin = Binary files: Position used as reference for the offset, must be
one of $(REF_ALTTEXT SEEK_SET, SEEK_SET, core,stdc,stdio),
$(REF_ALTTEXT SEEK_CUR, SEEK_CUR, core,stdc,stdio) or
$(REF_ALTTEXT SEEK_END, SEEK_END, core,stdc,stdio).$(BR)
Text files: Shall necessarily be
$(REF_ALTTEXT SEEK_SET, SEEK_SET, core,stdc,stdio).
Throws: `Exception` if the file is not opened.
`ErrnoException` if the call to `fseek` fails.
*/
void seek(long offset, int origin = SEEK_SET) @trusted
{
import std.conv : to, text;
import std.exception : enforce, errnoEnforce;
// Some libc sanitize the whence input (e.g. glibc), but some don't,
// e.g. Microsoft runtime crashes on an invalid origin,
// and Musl additionally accept SEEK_DATA & SEEK_HOLE (Linux extension).
// To provide a consistent behavior cross platform, we use the glibc check
// See also https://issues.dlang.org/show_bug.cgi?id=19797
enforce(origin == SEEK_SET || origin == SEEK_CUR || origin == SEEK_END,
"Invalid `origin` argument passed to `seek`, must be one of: SEEK_SET, SEEK_CUR, SEEK_END");
enforce(isOpen, "Attempting to seek() in an unopened file");
version (Windows)
{
version (CRuntime_Microsoft)
{
alias fseekFun = _fseeki64;
alias off_t = long;
}
else
{
alias fseekFun = fseek;
alias off_t = int;
}
}
else version (Posix)
{
import core.sys.posix.stdio : fseeko, off_t;
alias fseekFun = fseeko;
}
errnoEnforce(fseekFun(_p.handle, to!off_t(offset), origin) == 0,
"Could not seek in file `"~_name~"'");
}
@system unittest
{
import std.conv : text;
static import std.file;
import std.exception;
auto deleteme = testFilename();
auto f = File(deleteme, "w+");
scope(exit) { f.close(); std.file.remove(deleteme); }
f.rawWrite("abcdefghijklmnopqrstuvwxyz");
f.seek(7);
assert(f.readln() == "hijklmnopqrstuvwxyz");
version (CRuntime_Bionic)
auto bigOffset = int.max - 100;
else
auto bigOffset = cast(ulong) int.max + 100;
f.seek(bigOffset);
assert(f.tell == bigOffset, text(f.tell));
// Uncomment the tests below only if you want to wait for
// a long time
// f.rawWrite("abcdefghijklmnopqrstuvwxyz");
// f.seek(-3, SEEK_END);
// assert(f.readln() == "xyz");
assertThrown(f.seek(0, ushort.max));
}
/**
Calls $(CSTDIO ftell)
for the managed file handle, which returns the current value of
the position indicator of the file handle.
Throws: `Exception` if the file is not opened.
`ErrnoException` if the call to `ftell` fails.
*/
@property ulong tell() const @trusted
{
import std.exception : enforce, errnoEnforce;
enforce(isOpen, "Attempting to tell() in an unopened file");
version (Windows)
{
version (CRuntime_Microsoft)
immutable result = _ftelli64(cast(FILE*) _p.handle);
else
immutable result = ftell(cast(FILE*) _p.handle);
}
else version (Posix)
{
import core.sys.posix.stdio : ftello;
immutable result = ftello(cast(FILE*) _p.handle);
}
errnoEnforce(result != -1,
"Query ftell() failed for file `"~_name~"'");
return result;
}
///
@system unittest
{
import std.conv : text;
static import std.file;
auto testFile = std.file.deleteme();
std.file.write(testFile, "abcdefghijklmnopqrstuvwqxyz");
scope(exit) { std.file.remove(testFile); }
auto f = File(testFile);
auto a = new ubyte[4];
f.rawRead(a);
assert(f.tell == 4, text(f.tell));
}
/**
Calls $(CSTDIO rewind) for the file handle.
Throws: `Exception` if the file is not opened.
*/
void rewind() @safe
{
import std.exception : enforce;
enforce(isOpen, "Attempting to rewind() an unopened file");
.rewind(_p.handle);
}
/**
Calls $(CSTDIO setvbuf) for the file handle.
Throws: `Exception` if the file is not opened.
`ErrnoException` if the call to `setvbuf` fails.
*/
void setvbuf(size_t size, int mode = _IOFBF) @trusted
{
import std.exception : enforce, errnoEnforce;
enforce(isOpen, "Attempting to call setvbuf() on an unopened file");
errnoEnforce(.setvbuf(_p.handle, null, mode, size) == 0,
"Could not set buffering for file `"~_name~"'");
}
/**
Calls $(CSTDIO setvbuf) for the file handle.
Throws: `Exception` if the file is not opened.
`ErrnoException` if the call to `setvbuf` fails.
*/
void setvbuf(void[] buf, int mode = _IOFBF) @trusted
{
import std.exception : enforce, errnoEnforce;
enforce(isOpen, "Attempting to call setvbuf() on an unopened file");
errnoEnforce(.setvbuf(_p.handle,
cast(char*) buf.ptr, mode, buf.length) == 0,
"Could not set buffering for file `"~_name~"'");
}
version (Windows)
{
import core.sys.windows.winbase : OVERLAPPED;
import core.sys.windows.winnt : BOOL, ULARGE_INTEGER;
import std.windows.syserror : wenforce;
private BOOL lockImpl(alias F, Flags...)(ulong start, ulong length,
Flags flags)
{
if (!start && !length)
length = ulong.max;
ULARGE_INTEGER liStart = void, liLength = void;
liStart.QuadPart = start;
liLength.QuadPart = length;
OVERLAPPED overlapped;
overlapped.Offset = liStart.LowPart;
overlapped.OffsetHigh = liStart.HighPart;
overlapped.hEvent = null;
return F(windowsHandle, flags, 0, liLength.LowPart,
liLength.HighPart, &overlapped);
}
}
version (Posix)
{
private int lockImpl(int operation, short l_type,
ulong start, ulong length)
{
import core.sys.posix.fcntl : fcntl, flock, off_t;
import core.sys.posix.unistd : getpid;
import std.conv : to;
flock fl = void;
fl.l_type = l_type;
fl.l_whence = SEEK_SET;
fl.l_start = to!off_t(start);
fl.l_len = to!off_t(length);
fl.l_pid = getpid();
return fcntl(fileno, operation, &fl);
}
}
/**
Locks the specified file segment. If the file segment is already locked
by another process, waits until the existing lock is released.
If both `start` and `length` are zero, the entire file is locked.
Locks created using `lock` and `tryLock` have the following properties:
$(UL
$(LI All locks are automatically released when the process terminates.)
$(LI Locks are not inherited by child processes.)
$(LI Closing a file will release all locks associated with the file. On POSIX,
even locks acquired via a different `File` will be released as well.)
$(LI Not all NFS implementations correctly implement file locking.)
)
*/
void lock(LockType lockType = LockType.readWrite,
ulong start = 0, ulong length = 0)
{
import std.exception : enforce;
enforce(isOpen, "Attempting to call lock() on an unopened file");
version (Posix)
{
import core.sys.posix.fcntl : F_RDLCK, F_SETLKW, F_WRLCK;
import std.exception : errnoEnforce;
immutable short type = lockType == LockType.readWrite
? F_WRLCK : F_RDLCK;
errnoEnforce(lockImpl(F_SETLKW, type, start, length) != -1,
"Could not set lock for file `"~_name~"'");
}
else
version (Windows)
{
import core.sys.windows.winbase : LockFileEx, LOCKFILE_EXCLUSIVE_LOCK;
immutable type = lockType == LockType.readWrite ?
LOCKFILE_EXCLUSIVE_LOCK : 0;
wenforce(lockImpl!LockFileEx(start, length, type),
"Could not set lock for file `"~_name~"'");
}
else
static assert(false);
}
/**
Attempts to lock the specified file segment.
If both `start` and `length` are zero, the entire file is locked.
Returns: `true` if the lock was successful, and `false` if the
specified file segment was already locked.
*/
bool tryLock(LockType lockType = LockType.readWrite,
ulong start = 0, ulong length = 0)
{
import std.exception : enforce;
enforce(isOpen, "Attempting to call tryLock() on an unopened file");
version (Posix)
{
import core.stdc.errno : EACCES, EAGAIN, errno;
import core.sys.posix.fcntl : F_RDLCK, F_SETLK, F_WRLCK;
import std.exception : errnoEnforce;
immutable short type = lockType == LockType.readWrite
? F_WRLCK : F_RDLCK;
immutable res = lockImpl(F_SETLK, type, start, length);
if (res == -1 && (errno == EACCES || errno == EAGAIN))
return false;
errnoEnforce(res != -1, "Could not set lock for file `"~_name~"'");
return true;
}
else
version (Windows)
{
import core.sys.windows.winbase : GetLastError, LockFileEx, LOCKFILE_EXCLUSIVE_LOCK,
LOCKFILE_FAIL_IMMEDIATELY;
import core.sys.windows.winerror : ERROR_IO_PENDING, ERROR_LOCK_VIOLATION;
immutable type = lockType == LockType.readWrite
? LOCKFILE_EXCLUSIVE_LOCK : 0;
immutable res = lockImpl!LockFileEx(start, length,
type | LOCKFILE_FAIL_IMMEDIATELY);
if (!res && (GetLastError() == ERROR_IO_PENDING
|| GetLastError() == ERROR_LOCK_VIOLATION))
return false;
wenforce(res, "Could not set lock for file `"~_name~"'");
return true;
}
else
static assert(false);
}
/**
Removes the lock over the specified file segment.
*/
void unlock(ulong start = 0, ulong length = 0)
{
import std.exception : enforce;
enforce(isOpen, "Attempting to call unlock() on an unopened file");
version (Posix)
{
import core.sys.posix.fcntl : F_SETLK, F_UNLCK;
import std.exception : errnoEnforce;
errnoEnforce(lockImpl(F_SETLK, F_UNLCK, start, length) != -1,
"Could not remove lock for file `"~_name~"'");
}
else
version (Windows)
{
import core.sys.windows.winbase : UnlockFileEx;
wenforce(lockImpl!UnlockFileEx(start, length),
"Could not remove lock for file `"~_name~"'");
}
else
static assert(false);
}
version (Windows)
@system unittest
{
static import std.file;
auto deleteme = testFilename();
scope(exit) std.file.remove(deleteme);
auto f = File(deleteme, "wb");
assert(f.tryLock());
auto g = File(deleteme, "wb");
assert(!g.tryLock());
assert(!g.tryLock(LockType.read));
f.unlock();
f.lock(LockType.read);
assert(!g.tryLock());
assert(g.tryLock(LockType.read));
f.unlock();
g.unlock();
}
version (Posix)
@system unittest
{
static if (__traits(compiles, { import std.process : spawnProcess; }))
{
static import std.file;
auto deleteme = testFilename();
scope(exit) std.file.remove(deleteme);
// Since locks are per-process, we cannot test lock failures within
// the same process. fork() is used to create a second process.
static void runForked(void delegate() code)
{
import core.sys.posix.sys.wait : waitpid;
import core.sys.posix.unistd : fork, _exit;
int child, status;
if ((child = fork()) == 0)
{
code();
_exit(0);
}
else
{
assert(waitpid(child, &status, 0) != -1);
assert(status == 0, "Fork crashed");
}
}
auto f = File(deleteme, "w+b");
runForked
({
auto g = File(deleteme, "a+b");
assert(g.tryLock());
g.unlock();
assert(g.tryLock(LockType.read));
});
assert(f.tryLock());
runForked
({
auto g = File(deleteme, "a+b");
assert(!g.tryLock());
assert(!g.tryLock(LockType.read));
});
f.unlock();
f.lock(LockType.read);
runForked
({
auto g = File(deleteme, "a+b");
assert(!g.tryLock());
assert(g.tryLock(LockType.read));
g.unlock();
});
f.unlock();
} // static if
} // unittest
/**
Writes its arguments in text format to the file.
Throws: `Exception` if the file is not opened.
`ErrnoException` on an error writing to the file.
*/
void write(S...)(S args)
{
import std.traits : isBoolean, isIntegral, isAggregateType;
import std.utf : UTFException;
auto w = lockingTextWriter();
foreach (arg; args)
{
try
{
alias A = typeof(arg);
static if (isAggregateType!A || is(A == enum))
{
import std.format.write : formattedWrite;
formattedWrite(w, "%s", arg);
}
else static if (isSomeString!A)
{
put(w, arg);
}
else static if (isIntegral!A)
{
import std.conv : toTextRange;
toTextRange(arg, w);
}
else static if (isBoolean!A)
{
put(w, arg ? "true" : "false");
}
else static if (isSomeChar!A)
{
put(w, arg);
}
else
{
import std.format.write : formattedWrite;
// Most general case
formattedWrite(w, "%s", arg);
}
}
catch (UTFException e)
{
/* Reset the writer so that it doesn't throw another
UTFException on destruction. */
w.highSurrogate = '\0';
throw e;
}
}
}
/**
Writes its arguments in text format to the file, followed by a newline.
Throws: `Exception` if the file is not opened.
`ErrnoException` on an error writing to the file.
*/
void writeln(S...)(S args)
{
write(args, '\n');
}
/**
Writes its arguments in text format to the file, according to the
format string fmt.
Params:
fmt = The $(REF_ALTTEXT format string, formattedWrite, std, _format).
When passed as a compile-time argument, the string will be statically checked
against the argument types passed.
args = Items to write.
Throws: `Exception` if the file is not opened.
`ErrnoException` on an error writing to the file.
*/
void writef(alias fmt, A...)(A args)
if (isSomeString!(typeof(fmt)))
{
import std.format : checkFormatException;
alias e = checkFormatException!(fmt, A);
static assert(!e, e);
return this.writef(fmt, args);
}
/// ditto
void writef(Char, A...)(in Char[] fmt, A args)
{
import std.format.write : formattedWrite;
formattedWrite(lockingTextWriter(), fmt, args);
}
/// Equivalent to `file.writef(fmt, args, '\n')`.
void writefln(alias fmt, A...)(A args)
if (isSomeString!(typeof(fmt)))
{
import std.format : checkFormatException;
alias e = checkFormatException!(fmt, A);
static assert(!e, e);
return this.writefln(fmt, args);
}
/// ditto
void writefln(Char, A...)(in Char[] fmt, A args)
{
import std.format.write : formattedWrite;
auto w = lockingTextWriter();
formattedWrite(w, fmt, args);
w.put('\n');
}
/**
Read line from the file handle and return it as a specified type.
This version manages its own read buffer, which means one memory allocation per call. If you are not
retaining a reference to the read data, consider the `File.readln(buf)` version, which may offer
better performance as it can reuse its read buffer.
Params:
S = Template parameter; the type of the allocated buffer, and the type returned. Defaults to `string`.
terminator = Line terminator (by default, `'\n'`).
Note:
String terminators are not supported due to ambiguity with readln(buf) below.
Returns:
The line that was read, including the line terminator character.
Throws:
`StdioException` on I/O error, or `UnicodeException` on Unicode conversion error.
Example:
---
// Reads `stdin` and writes it to `stdout`.
import std.stdio;
void main()
{
string line;
while ((line = stdin.readln()) !is null)
write(line);
}
---
*/
S readln(S = string)(dchar terminator = '\n') @safe
if (isSomeString!S)
{
Unqual!(ElementEncodingType!S)[] buf;
readln(buf, terminator);
return (() @trusted => cast(S) buf)();
}
@safe unittest
{
import std.algorithm.comparison : equal;
static import std.file;
import std.meta : AliasSeq;
auto deleteme = testFilename();
std.file.write(deleteme, "hello\nworld\n");
scope(exit) std.file.remove(deleteme);
static foreach (String; AliasSeq!(string, char[], wstring, wchar[], dstring, dchar[]))
{{
auto witness = [ "hello\n", "world\n" ];
auto f = File(deleteme);
uint i = 0;
String buf;
while ((buf = f.readln!String()).length)
{
assert(i < witness.length);
assert(equal(buf, witness[i++]));
}
assert(i == witness.length);
}}
}
@safe unittest
{
static import std.file;
import std.typecons : Tuple;
auto deleteme = testFilename();
std.file.write(deleteme, "cześć \U0002000D");
scope(exit) std.file.remove(deleteme);
uint[] lengths = [12,8,7];
static foreach (uint i, C; Tuple!(char, wchar, dchar).Types)
{{
immutable(C)[] witness = "cześć \U0002000D";
auto buf = File(deleteme).readln!(immutable(C)[])();
assert(buf.length == lengths[i]);
assert(buf == witness);
}}
}
/**
Read line from the file handle and write it to `buf[]`, including
terminating character.
This can be faster than $(D line = File.readln()) because you can reuse
the buffer for each call. Note that reusing the buffer means that you
must copy the previous contents if you wish to retain them.
Params:
buf = Buffer used to store the resulting line data. buf is
enlarged if necessary, then set to the slice exactly containing the line.
terminator = Line terminator (by default, `'\n'`). Use
$(REF newline, std,ascii) for portability (unless the file was opened in
text mode).
Returns:
0 for end of file, otherwise number of characters read.
The return value will always be equal to `buf.length`.
Throws: `StdioException` on I/O error, or `UnicodeException` on Unicode
conversion error.
Example:
---
// Read lines from `stdin` into a string
// Ignore lines starting with '#'
// Write the string to `stdout`
import std.stdio;
void main()
{
string output;
char[] buf;
while (stdin.readln(buf))
{
if (buf[0] == '#')
continue;
output ~= buf;
}
write(output);
}
---
This method can be more efficient than the one in the previous example
because `stdin.readln(buf)` reuses (if possible) memory allocated
for `buf`, whereas $(D line = stdin.readln()) makes a new memory allocation
for every line.
For even better performance you can help `readln` by passing in a
large buffer to avoid memory reallocations. This can be done by reusing the
largest buffer returned by `readln`:
Example:
---
// Read lines from `stdin` and count words
import std.array, std.stdio;
void main()
{
char[] buf;
size_t words = 0;
while (!stdin.eof)
{
char[] line = buf;
stdin.readln(line);
if (line.length > buf.length)
buf = line;
words += line.split.length;
}
writeln(words);
}
---
This is actually what $(LREF byLine) does internally, so its usage
is recommended if you want to process a complete file.
*/
size_t readln(C)(ref C[] buf, dchar terminator = '\n') @safe
if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum))
{
import std.exception : enforce;
static if (is(C == char))
{
enforce(_p && _p.handle, "Attempt to read from an unopened file.");
if (_p.orientation == Orientation.unknown)
{
import core.stdc.wchar_ : fwide;
auto w = fwide(_p.handle, 0);
if (w < 0) _p.orientation = Orientation.narrow;
else if (w > 0) _p.orientation = Orientation.wide;
}
return readlnImpl(_p.handle, buf, terminator, _p.orientation);
}
else
{
string s = readln(terminator);
if (!s.length)
{
buf = buf[0 .. 0];
return 0;
}
import std.utf : codeLength;
buf.length = codeLength!C(s);
size_t idx;
foreach (C c; s)
buf[idx++] = c;
return buf.length;
}
}
@safe unittest
{
static import std.file;
auto deleteme = testFilename();
std.file.write(deleteme, "123\n456789");
scope(exit) std.file.remove(deleteme);
auto file = File(deleteme);
char[] buffer = new char[10];
char[] line = buffer;
file.readln(line);
auto beyond = line.length;
buffer[beyond] = 'a';
file.readln(line); // should not write buffer beyond line
assert(buffer[beyond] == 'a');
}
// https://issues.dlang.org/show_bug.cgi?id=15293
@safe unittest
{
// @system due to readln
static import std.file;
auto deleteme = testFilename();
std.file.write(deleteme, "a\n\naa");
scope(exit) std.file.remove(deleteme);
auto file = File(deleteme);
char[] buffer;
char[] line;
file.readln(buffer, '\n');
line = buffer;
file.readln(line, '\n');
line = buffer;
file.readln(line, '\n');
assert(line[0 .. 1].capacity == 0);
}
/** ditto */
size_t readln(C, R)(ref C[] buf, R terminator) @safe
if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum) &&
isBidirectionalRange!R && is(typeof(terminator.front == dchar.init)))
{
import std.algorithm.mutation : swap;
import std.algorithm.searching : endsWith;
import std.range.primitives : back;
auto last = terminator.back;
C[] buf2;
swap(buf, buf2);
for (;;)
{
if (!readln(buf2, last) || endsWith(buf2, terminator))
{
if (buf.empty)
{
buf = buf2;
}
else
{
buf ~= buf2;
}
break;
}
buf ~= buf2;
}
return buf.length;
}
@safe unittest
{
static import std.file;
import std.typecons : Tuple;
auto deleteme = testFilename();
std.file.write(deleteme, "hello\n\rworld\nhow\n\rare ya");
scope(exit) std.file.remove(deleteme);
foreach (C; Tuple!(char, wchar, dchar).Types)
{
immutable(C)[][] witness = [ "hello\n\r", "world\nhow\n\r", "are ya" ];
auto f = File(deleteme);
uint i = 0;
C[] buf;
while (f.readln(buf, "\n\r"))
{
assert(i < witness.length);
assert(buf == witness[i++]);
}
assert(buf.length == 0);
}
}
/**
* Reads formatted _data from the file using $(REF formattedRead, std,_format).
* Params:
* format = The $(REF_ALTTEXT format string, formattedWrite, std, _format).
* When passed as a compile-time argument, the string will be statically checked
* against the argument types passed.
* data = Items to be read.
* Returns:
* Same as `formattedRead`: The number of variables filled. If the input range `r` ends early,
* this number will be less than the number of variables provided.
* Example:
----
// test.d
void main()
{
import std.stdio;
auto f = File("input");
foreach (_; 0 .. 3)
{
int a;
f.readf!" %d"(a);
writeln(++a);
}
}
----
$(CONSOLE
% echo "1 2 3" > input
% rdmd test.d
2
3
4
)
*/
uint readf(alias format, Data...)(auto ref Data data)
if (isSomeString!(typeof(format)))
{
import std.format : checkFormatException;
alias e = checkFormatException!(format, Data);
static assert(!e, e);
return this.readf(format, data);
}
/// ditto
uint readf(Data...)(scope const(char)[] format, auto ref Data data)
{
import std.format.read : formattedRead;
assert(isOpen);
auto input = LockingTextReader(this);
return formattedRead(input, format, data);
}
///
@system unittest
{
static import std.file;
auto deleteme = std.file.deleteme();
std.file.write(deleteme, "hello\nworld\ntrue\nfalse\n");
scope(exit) std.file.remove(deleteme);
string s;
auto f = File(deleteme);
f.readf!"%s\n"(s);
assert(s == "hello", "["~s~"]");
f.readf("%s\n", s);
assert(s == "world", "["~s~"]");
bool b1, b2;
f.readf("%s\n%s\n", b1, b2);
assert(b1 == true && b2 == false);
}
// backwards compatibility with pointers
@system unittest
{
// @system due to readf
static import std.file;
auto deleteme = testFilename();
std.file.write(deleteme, "hello\nworld\ntrue\nfalse\n");
scope(exit) std.file.remove(deleteme);
string s;
auto f = File(deleteme);
f.readf("%s\n", &s);
assert(s == "hello", "["~s~"]");
f.readf("%s\n", &s);
assert(s == "world", "["~s~"]");
// https://issues.dlang.org/show_bug.cgi?id=11698
bool b1, b2;
f.readf("%s\n%s\n", &b1, &b2);
assert(b1 == true && b2 == false);
}
// backwards compatibility (mixed)
@system unittest
{
// @system due to readf
static import std.file;
auto deleteme = testFilename();
std.file.write(deleteme, "hello\nworld\ntrue\nfalse\n");
scope(exit) std.file.remove(deleteme);
string s1, s2;
auto f = File(deleteme);
f.readf("%s\n%s\n", s1, &s2);
assert(s1 == "hello");
assert(s2 == "world");
// https://issues.dlang.org/show_bug.cgi?id=11698
bool b1, b2;
f.readf("%s\n%s\n", &b1, b2);
assert(b1 == true && b2 == false);
}
// Nice error of std.stdio.readf with newlines
// https://issues.dlang.org/show_bug.cgi?id=12260
@system unittest
{
static import std.file;
auto deleteme = testFilename();
std.file.write(deleteme, "1\n2");
scope(exit) std.file.remove(deleteme);
int input;
auto f = File(deleteme);
f.readf("%s", &input);
import std.conv : ConvException;
import std.exception : collectException;
assert(collectException!ConvException(f.readf("%s", &input)).msg ==
"Unexpected '\\n' when converting from type LockingTextReader to type int");
}
/**
Reads a line from the file and parses it using $(REF formattedRead, std,format,read).
Params:
format = The $(MREF_ALTTEXT format string, std,format). When passed as a
compile-time argument, the string will be statically checked against the
argument types passed.
data = Items to be read.
Returns: Same as `formattedRead`: the number of variables filled. If the
input ends early, this number will be less that the number of variables
provided.
Example:
---
// sum_rows.d
void main()
{
import std.stdio;
auto f = File("input");
int a, b, c;
while (f.readfln("%d %d %d", a, b, c) == 3)
{
writeln(a + b + c);
}
}
---
$(CONSOLE
% cat << EOF > input
1 2 3
4 5 6
7 8 9
EOF
% rdmd sum_rows.d
6
15
24
)
*/
uint readfln(alias format, Data...)(auto ref Data data)
if (isSomeString!(typeof(format)))
{
import std.format : checkFormatException;
alias e = checkFormatException!(format, Data);
static assert(!e, e);
return this.readfln(format, data);
}
/// ditto
uint readfln(Data...)(scope const(char)[] format, auto ref Data data)
{
import std.format.read : formattedRead;
import std.string : stripRight;
string line = this.readln.stripRight("\r\n");
return formattedRead(line, format, data);
}
@system unittest
{
static import std.file;
auto deleteme = testFilename();
std.file.write(deleteme, "hello\nworld\ntrue\nfalse\n");
scope(exit) std.file.remove(deleteme);
string s;
auto f = File(deleteme);
f.readfln!"%s"(s);
assert(s == "hello", "["~s~"]");
f.readfln("%s", s);
assert(s == "world", "["~s~"]");
bool b1, b2;
f.readfln("%s", b1);
f.readfln("%s", b2);
assert(b1 == true && b2 == false);
}
/**
Returns a temporary file by calling $(CSTDIO tmpfile).
Note that the created file has no $(LREF name).*/
static File tmpfile() @safe
{
import std.exception : errnoEnforce;
return File(errnoEnforce(.tmpfile(),
"Could not create temporary file with tmpfile()"),
null);
}
/**
Unsafe function that wraps an existing `FILE*`. The resulting $(D
File) never takes the initiative in closing the file.
Note that the created file has no $(LREF name)*/
/*private*/ static File wrapFile(FILE* f) @safe
{
import std.exception : enforce;
return File(enforce(f, "Could not wrap null FILE*"),
null, /*uint.max / 2*/ 9999);
}
/**
Returns the `FILE*` corresponding to this object.
*/
FILE* getFP() @safe pure
{
import std.exception : enforce;
enforce(_p && _p.handle,
"Attempting to call getFP() on an unopened file");
return _p.handle;
}
@system unittest
{
static import core.stdc.stdio;
assert(stdout.getFP() == core.stdc.stdio.stdout);
}
/**
Returns the file number corresponding to this object.
*/
@property fileno_t fileno() const @trusted
{
import std.exception : enforce;
enforce(isOpen, "Attempting to call fileno() on an unopened file");
return .fileno(cast(FILE*) _p.handle);
}
/**
Returns the underlying operating system `HANDLE` (Windows only).
*/
version (StdDdoc)
@property HANDLE windowsHandle();
version (Windows)
@property HANDLE windowsHandle()
{
return cast(HANDLE)_get_osfhandle(fileno);
}
// Note: This was documented until 2013/08
/*
Range that reads one line at a time. Returned by $(LREF byLine).
Allows to directly use range operations on lines of a file.
*/
private struct ByLineImpl(Char, Terminator)
{
private:
import std.typecons : borrow, RefCountedAutoInitialize, SafeRefCounted;
/* Ref-counting stops the source range's Impl
* from getting out of sync after the range is copied, e.g.
* when accessing range.front, then using std.range.take,
* then accessing range.front again. */
alias PImpl = SafeRefCounted!(Impl, RefCountedAutoInitialize.no);
PImpl impl;
static if (isScalarType!Terminator)
enum defTerm = '\n';
else
enum defTerm = cast(Terminator)"\n";
public:
this(File f, KeepTerminator kt = No.keepTerminator,
Terminator terminator = defTerm)
{
impl = PImpl(f, kt, terminator);
}
/* Verifiably `@safe` when built with -preview=DIP1000. */
@property bool empty() @trusted
{
// Using `ref` is actually necessary here.
return impl.borrow!((ref i) => i.empty);
}
/* Verifiably `@safe` when built with -preview=DIP1000. */
@property Char[] front() @trusted
{
// Using `ref` is likely optional here.
return impl.borrow!((ref i) => i.front);
}
/* Verifiably `@safe` when built with -preview=DIP1000. */
void popFront() @trusted
{
return impl.borrow!((ref i) => i.popFront());
}
private:
struct Impl
{
private:
File file;
Char[] line;
Char[] buffer;
Terminator terminator;
KeepTerminator keepTerminator;
bool haveLine;
@safe:
public:
this(File f, KeepTerminator kt, Terminator terminator)
{
file = f;
this.terminator = terminator;
keepTerminator = kt;
}
// Range primitive implementations.
@property bool empty()
{
needLine();
return line is null;
}
@property Char[] front()
{
needLine();
return line;
}
void popFront()
{
needLine();
haveLine = false;
}
private:
void needLine()
{
if (haveLine)
return;
import std.algorithm.searching : endsWith;
assert(file.isOpen);
line = buffer;
file.readln(line, terminator);
if (line.length > buffer.length)
{
buffer = line;
}
if (line.empty)
{
file.detach();
line = null;
}
else if (keepTerminator == No.keepTerminator
&& endsWith(line, terminator))
{
static if (isScalarType!Terminator)
enum tlen = 1;
else static if (isArray!Terminator)
{
static assert(
is(immutable ElementEncodingType!Terminator == immutable Char));
const tlen = terminator.length;
}
else
static assert(false);
line = line[0 .. line.length - tlen];
}
haveLine = true;
}
}
}
/**
Returns an $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
set up to read from the file handle one line at a time.
The element type for the range will be `Char[]`. Range primitives
may throw `StdioException` on I/O error.
Note:
Each `front` will not persist after $(D
popFront) is called, so the caller must copy its contents (e.g. by
calling `to!string`) when retention is needed. If the caller needs
to retain a copy of every line, use the $(LREF byLineCopy) function
instead.
Params:
Char = Character type for each line, defaulting to `char`.
keepTerminator = Use `Yes.keepTerminator` to include the
terminator at the end of each line.
terminator = Line separator (`'\n'` by default). Use
$(REF newline, std,ascii) for portability (unless the file was opened in
text mode).
Example:
----
import std.algorithm, std.stdio, std.string;
// Count words in a file using ranges.
void main()
{
auto file = File("file.txt"); // Open for reading
const wordCount = file.byLine() // Read lines
.map!split // Split into words
.map!(a => a.length) // Count words per line
.sum(); // Total word count
writeln(wordCount);
}
----
Example:
----
import std.range, std.stdio;
// Read lines using foreach.
void main()
{
auto file = File("file.txt"); // Open for reading
auto range = file.byLine();
// Print first three lines
foreach (line; range.take(3))
writeln(line);
// Print remaining lines beginning with '#'
foreach (line; range)
{
if (!line.empty && line[0] == '#')
writeln(line);
}
}
----
Notice that neither example accesses the line data returned by
`front` after the corresponding `popFront` call is made (because
the contents may well have changed).
----
Windows specific Example:
----
import std.stdio;
version (Windows)
void main()
{
foreach (line; File("file.txt").byLine(No.keepTerminator, "\r\n"))
{
writeln("|"~line~"|");
if (line == "HelloWorld")
writeln("^This Line is here.");
}
}
*/
auto byLine(Terminator = char, Char = char)
(KeepTerminator keepTerminator = No.keepTerminator,
Terminator terminator = '\n')
if (isScalarType!Terminator)
{
return ByLineImpl!(Char, Terminator)(this, keepTerminator, terminator);
}
/// ditto
auto byLine(Terminator, Char = char)
(KeepTerminator keepTerminator, Terminator terminator)
if (is(immutable ElementEncodingType!Terminator == immutable Char))
{
return ByLineImpl!(Char, Terminator)(this, keepTerminator, terminator);
}
@safe unittest
{
static import std.file;
auto deleteme = testFilename();
std.file.write(deleteme, "hi");
scope(success) std.file.remove(deleteme);
import std.meta : AliasSeq;
static foreach (T; AliasSeq!(char, wchar, dchar))
{{
auto blc = File(deleteme).byLine!(T, T);
assert(blc.front == "hi");
// check front is cached
assert(blc.front is blc.front);
}}
}
// https://issues.dlang.org/show_bug.cgi?id=19980
@safe unittest
{
static import std.file;
auto deleteme = testFilename();
std.file.write(deleteme, "Line 1\nLine 2\nLine 3\n");
scope(success) std.file.remove(deleteme);
auto f = File(deleteme);
f.byLine();
f.byLine();
assert(f.byLine().front == "Line 1");
}
private struct ByLineCopy(Char, Terminator)
{
private:
import std.typecons : borrow, RefCountedAutoInitialize, SafeRefCounted;
/* Ref-counting stops the source range's ByLineCopyImpl
* from getting out of sync after the range is copied, e.g.
* when accessing range.front, then using std.range.take,
* then accessing range.front again. */
alias Impl = SafeRefCounted!(ByLineCopyImpl!(Char, Terminator),
RefCountedAutoInitialize.no);
Impl impl;
public:
this(File f, KeepTerminator kt, Terminator terminator)
{
impl = Impl(f, kt, terminator);
}
/* Verifiably `@safe` when built with -preview=DIP1000. */
@property bool empty() @trusted
{
// Using `ref` is actually necessary here.
return impl.borrow!((ref i) => i.empty);
}
/* Verifiably `@safe` when built with -preview=DIP1000. */
@property Char[] front() @trusted
{
// Using `ref` is likely optional here.
return impl.borrow!((ref i) => i.front);
}
/* Verifiably `@safe` when built with -preview=DIP1000. */
void popFront() @trusted
{
impl.borrow!((ref i) => i.popFront());
}
}
private struct ByLineCopyImpl(Char, Terminator)
{
ByLineImpl!(Unqual!Char, Terminator).Impl impl;
bool gotFront;
Char[] line;
public:
this(File f, KeepTerminator kt, Terminator terminator)
{
impl = ByLineImpl!(Unqual!Char, Terminator).Impl(f, kt, terminator);
}
@property bool empty()
{
return impl.empty;
}
@property front()
{
if (!gotFront)
{
line = impl.front.dup;
gotFront = true;
}
return line;
}
void popFront()
{
impl.popFront();
gotFront = false;
}
}
/**
Returns an $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
set up to read from the file handle one line
at a time. Each line will be newly allocated. `front` will cache
its value to allow repeated calls without unnecessary allocations.
Note: Due to caching byLineCopy can be more memory-efficient than
`File.byLine.map!idup`.
The element type for the range will be `Char[]`. Range
primitives may throw `StdioException` on I/O error.
Params:
Char = Character type for each line, defaulting to $(D immutable char).
keepTerminator = Use `Yes.keepTerminator` to include the
terminator at the end of each line.
terminator = Line separator (`'\n'` by default). Use
$(REF newline, std,ascii) for portability (unless the file was opened in
text mode).
Example:
----
import std.algorithm, std.array, std.stdio;
// Print sorted lines of a file.
void main()
{
auto sortedLines = File("file.txt") // Open for reading
.byLineCopy() // Read persistent lines
.array() // into an array
.sort(); // then sort them
foreach (line; sortedLines)
writeln(line);
}
----
See_Also:
$(REF readText, std,file)
*/
auto byLineCopy(Terminator = char, Char = immutable char)
(KeepTerminator keepTerminator = No.keepTerminator,
Terminator terminator = '\n')
if (isScalarType!Terminator)
{
return ByLineCopy!(Char, Terminator)(this, keepTerminator, terminator);
}
/// ditto
auto byLineCopy(Terminator, Char = immutable char)
(KeepTerminator keepTerminator, Terminator terminator)
if (is(immutable ElementEncodingType!Terminator == immutable Char))
{
return ByLineCopy!(Char, Terminator)(this, keepTerminator, terminator);
}
@safe unittest
{
static assert(is(typeof(File("").byLine.front) == char[]));
static assert(is(typeof(File("").byLineCopy.front) == string));
static assert(
is(typeof(File("").byLineCopy!(char, char).front) == char[]));
}
@safe unittest
{
import std.algorithm.comparison : equal;
static import std.file;
auto deleteme = testFilename();
std.file.write(deleteme, "");
scope(success) std.file.remove(deleteme);
// Test empty file
auto f = File(deleteme);
foreach (line; f.byLine())
{
assert(false);
}
f.detach();
assert(!f.isOpen);
void test(Terminator)(string txt, in string[] witness,
KeepTerminator kt, Terminator term, bool popFirstLine = false)
{
import std.algorithm.sorting : sort;
import std.array : array;
import std.conv : text;
import std.range.primitives : walkLength;
uint i;
std.file.write(deleteme, txt);
auto f = File(deleteme);
scope(exit)
{
f.close();
assert(!f.isOpen);
}
auto lines = f.byLine(kt, term);
if (popFirstLine)
{
lines.popFront();
i = 1;
}
assert(lines.empty || lines.front is lines.front);
foreach (line; lines)
{
assert(line == witness[i++]);
}
assert(i == witness.length, text(i, " != ", witness.length));
// https://issues.dlang.org/show_bug.cgi?id=11830
auto walkedLength = File(deleteme).byLine(kt, term).walkLength;
assert(walkedLength == witness.length, text(walkedLength, " != ", witness.length));
// test persistent lines
assert(File(deleteme).byLineCopy(kt, term).array.sort() == witness.dup.sort());
}
KeepTerminator kt = No.keepTerminator;
test("", null, kt, '\n');
test("\n", [ "" ], kt, '\n');
test("asd\ndef\nasdf", [ "asd", "def", "asdf" ], kt, '\n');
test("asd\ndef\nasdf", [ "asd", "def", "asdf" ], kt, '\n', true);
test("asd\ndef\nasdf\n", [ "asd", "def", "asdf" ], kt, '\n');
test("foo", [ "foo" ], kt, '\n', true);
test("bob\r\nmarge\r\nsteve\r\n", ["bob", "marge", "steve"],
kt, "\r\n");
test("sue\r", ["sue"], kt, '\r');
kt = Yes.keepTerminator;
test("", null, kt, '\n');
test("\n", [ "\n" ], kt, '\n');
test("asd\ndef\nasdf", [ "asd\n", "def\n", "asdf" ], kt, '\n');
test("asd\ndef\nasdf\n", [ "asd\n", "def\n", "asdf\n" ], kt, '\n');
test("asd\ndef\nasdf\n", [ "asd\n", "def\n", "asdf\n" ], kt, '\n', true);
test("foo", [ "foo" ], kt, '\n');
test("bob\r\nmarge\r\nsteve\r\n", ["bob\r\n", "marge\r\n", "steve\r\n"],
kt, "\r\n");
test("sue\r", ["sue\r"], kt, '\r');
}
@safe unittest
{
import std.algorithm.comparison : equal;
import std.range : drop, take;
version (Win64)
{
static import std.file;
/* the C function tmpfile doesn't seem to work, even when called from C */
auto deleteme = testFilename();
auto file = File(deleteme, "w+");
scope(success) std.file.remove(deleteme);
}
else version (CRuntime_Bionic)
{
static import std.file;
/* the C function tmpfile doesn't work when called from a shared
library apk:
https://code.google.com/p/android/issues/detail?id=66815 */
auto deleteme = testFilename();
auto file = File(deleteme, "w+");
scope(success) std.file.remove(deleteme);
}
else
auto file = File.tmpfile();
file.write("1\n2\n3\n");
// https://issues.dlang.org/show_bug.cgi?id=9599
file.rewind();
File.ByLineImpl!(char, char) fbl = file.byLine();
auto fbl2 = fbl;
assert(fbl.front == "1");
assert(fbl.front is fbl2.front);
assert(fbl.take(1).equal(["1"]));
assert(fbl.equal(["2", "3"]));
assert(fbl.empty);
assert(file.isOpen); // we still have a valid reference
file.rewind();
fbl = file.byLine();
assert(!fbl.drop(2).empty);
assert(fbl.equal(["3"]));
assert(fbl.empty);
assert(file.isOpen);
file.detach();
assert(!file.isOpen);
}
@safe unittest
{
static import std.file;
auto deleteme = testFilename();
std.file.write(deleteme, "hi");
scope(success) std.file.remove(deleteme);
auto blc = File(deleteme).byLineCopy;
assert(!blc.empty);
// check front is cached
assert(blc.front is blc.front);
}
/**
Creates an $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
set up to parse one line at a time from the file into a tuple.
Range primitives may throw `StdioException` on I/O error.
Params:
format = tuple record $(REF_ALTTEXT _format, formattedRead, std, _format)
Returns:
The input range set up to parse one line at a time into a record tuple.
See_Also:
It is similar to $(LREF byLine) and uses
$(REF_ALTTEXT _format, formattedRead, std, _format) under the hood.
*/
template byRecord(Fields...)
{
auto byRecord(string format)
{
return ByRecordImpl!(Fields)(this, format);
}
}
///
@system unittest
{
static import std.file;
import std.typecons : tuple;
// prepare test file
auto testFile = std.file.deleteme();
scope(failure) printf("Failed test at line %d\n", __LINE__);
std.file.write(testFile, "1 2\n4 1\n5 100");
scope(exit) std.file.remove(testFile);
File f = File(testFile);
scope(exit) f.close();
auto expected = [tuple(1, 2), tuple(4, 1), tuple(5, 100)];
uint i;
foreach (e; f.byRecord!(int, int)("%s %s"))
{
assert(e == expected[i++]);
}
}
// Note: This was documented until 2013/08
/*
* Range that reads a chunk at a time.
*/
private struct ByChunkImpl
{
private:
File file_;
ubyte[] chunk_;
void prime()
{
chunk_ = file_.rawRead(chunk_);
if (chunk_.length == 0)
file_.detach();
}
public:
this(File file, size_t size)
{
this(file, new ubyte[](size));
}
this(File file, ubyte[] buffer)
{
import std.exception : enforce;
enforce(buffer.length, "size must be larger than 0");
file_ = file;
chunk_ = buffer;
prime();
}
// `ByChunk`'s input range primitive operations.
@property nothrow
bool empty() const
{
return !file_.isOpen;
}
/// Ditto
@property nothrow
ubyte[] front()
{
version (assert)
{
import core.exception : RangeError;
if (empty)
throw new RangeError();
}
return chunk_;
}
/// Ditto
void popFront()
{
version (assert)
{
import core.exception : RangeError;
if (empty)
throw new RangeError();
}
prime();
}
}
/**
Returns an $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
set up to read from the file handle a chunk at a time.
The element type for the range will be `ubyte[]`. Range primitives
may throw `StdioException` on I/O error.
Example:
---------
void main()
{
// Read standard input 4KB at a time
foreach (ubyte[] buffer; stdin.byChunk(4096))
{
... use buffer ...
}
}
---------
The parameter may be a number (as shown in the example above) dictating the
size of each chunk. Alternatively, `byChunk` accepts a
user-provided buffer that it uses directly.
Example:
---------
void main()
{
// Read standard input 4KB at a time
foreach (ubyte[] buffer; stdin.byChunk(new ubyte[4096]))
{
... use buffer ...
}
}
---------
In either case, the content of the buffer is reused across calls. That means
`front` will not persist after `popFront` is called, so if retention is
needed, the caller must copy its contents (e.g. by calling `buffer.dup`).
In the example above, `buffer.length` is 4096 for all iterations, except
for the last one, in which case `buffer.length` may be less than 4096 (but
always greater than zero).
With the mentioned limitations, `byChunk` works with any algorithm
compatible with input ranges.
Example:
---
// Efficient file copy, 1MB at a time.
import std.algorithm, std.stdio;
void main()
{
stdin.byChunk(1024 * 1024).copy(stdout.lockingTextWriter());
}
---
$(REF joiner, std,algorithm,iteration) can be used to join chunks together into
a single range lazily.
Example:
---
import std.algorithm, std.stdio;
void main()
{
//Range of ranges
static assert(is(typeof(stdin.byChunk(4096).front) == ubyte[]));
//Range of elements
static assert(is(typeof(stdin.byChunk(4096).joiner.front) == ubyte));
}
---
Returns: A call to `byChunk` returns a range initialized with the `File`
object and the appropriate buffer.
Throws: If the user-provided size is zero or the user-provided buffer
is empty, throws an `Exception`. In case of an I/O error throws
`StdioException`.
*/
auto byChunk(size_t chunkSize)
{
return ByChunkImpl(this, chunkSize);
}
/// Ditto
auto byChunk(ubyte[] buffer)
{
return ByChunkImpl(this, buffer);
}
@system unittest
{
static import std.file;
scope(failure) printf("Failed test at line %d\n", __LINE__);
auto deleteme = testFilename();
std.file.write(deleteme, "asd\ndef\nasdf");
auto witness = ["asd\n", "def\n", "asdf" ];
auto f = File(deleteme);
scope(exit)
{
f.close();
assert(!f.isOpen);
std.file.remove(deleteme);
}
uint i;
foreach (chunk; f.byChunk(4))
assert(chunk == cast(ubyte[]) witness[i++]);
assert(i == witness.length);
}
@system unittest
{
static import std.file;
scope(failure) printf("Failed test at line %d\n", __LINE__);
auto deleteme = testFilename();
std.file.write(deleteme, "asd\ndef\nasdf");
auto witness = ["asd\n", "def\n", "asdf" ];
auto f = File(deleteme);
scope(exit)
{
f.close();
assert(!f.isOpen);
std.file.remove(deleteme);
}
uint i;
foreach (chunk; f.byChunk(new ubyte[4]))
assert(chunk == cast(ubyte[]) witness[i++]);
assert(i == witness.length);
}
// Note: This was documented until 2013/08
/*
`Range` that locks the file and allows fast writing to it.
*/
struct LockingTextWriter
{
private:
import std.range.primitives : ElementType, isInfinite, isInputRange;
// Access the FILE* handle through the 'file_' member
// to keep the object alive through refcounting
File file_;
// the unshared version of FILE* handle, extracted from the File object
@property _iobuf* handle_() @trusted { return cast(_iobuf*) file_._p.handle; }
// the file's orientation (byte- or wide-oriented)
int orientation_;
// Buffers for when we need to transcode.
wchar highSurrogate = '\0'; // '\0' indicates empty
void highSurrogateShouldBeEmpty() @safe
{
import std.utf : UTFException;
if (highSurrogate != '\0')
throw new UTFException("unpaired surrogate UTF-16 value");
}
char[4] rbuf8;
size_t rbuf8Filled = 0;
public:
this(ref File f) @trusted
{
import std.exception : enforce;
enforce(f._p && f._p.handle, "Attempting to write to closed File");
file_ = f;
FILE* fps = f._p.handle;
version (CRuntime_Microsoft)
{
// Microsoft doesn't implement fwide. Instead, there's the
// concept of ANSI/UNICODE mode. fputc doesn't work in UNICODE
// mode; fputwc has to be used. So that essentially means
// "wide-oriented" for us.
immutable int mode = _setmode(f.fileno, _O_TEXT);
// Set some arbitrary mode to obtain the previous one.
if (mode != -1) // _setmode() succeeded
{
_setmode(f.fileno, mode); // Restore previous mode.
if (mode & (_O_WTEXT | _O_U16TEXT | _O_U8TEXT))
{
orientation_ = 1; // wide
}
}
}
else
{
import core.stdc.wchar_ : fwide;
orientation_ = fwide(fps, 0);
}
_FLOCK(fps);
}
~this() @trusted
{
if (auto p = file_._p)
{
if (p.handle) _FUNLOCK(p.handle);
}
file_ = File.init;
/* Destroy file_ before possibly throwing. Else it wouldn't be
destroyed, and its reference count would be wrong. */
highSurrogateShouldBeEmpty();
}
this(this) @trusted
{
if (auto p = file_._p)
{
if (p.handle) _FLOCK(p.handle);
}
}
/// Range primitive implementations.
void put(A)(scope A writeme)
if ((isSomeChar!(ElementType!A) ||
is(ElementType!A : const(ubyte))) &&
isInputRange!A &&
!isInfinite!A)
{
import std.exception : errnoEnforce;
alias C = ElementEncodingType!A;
static assert(!is(C == void));
static if (isSomeString!A && C.sizeof == 1 || is(A : const(ubyte)[]))
{
if (orientation_ <= 0)
{
//file.write(writeme); causes infinite recursion!!!
//file.rawWrite(writeme);
auto result = trustedFwrite(file_._p.handle, writeme);
if (result != writeme.length) errnoEnforce(0);
return;
}
}
// put each element in turn.
foreach (c; writeme)
{
put(c);
}
}
/// ditto
void put(C)(scope C c) @safe
if (isSomeChar!C || is(C : const(ubyte)))
{
import std.utf : decodeFront, encode, stride;
static if (c.sizeof == 1)
{
highSurrogateShouldBeEmpty();
if (orientation_ <= 0) trustedFPUTC(c, handle_);
else if (c <= 0x7F) trustedFPUTWC(c, handle_);
else if (c >= 0b1100_0000) // start byte of multibyte sequence
{
rbuf8[0] = c;
rbuf8Filled = 1;
}
else // continuation byte of multibyte sequence
{
rbuf8[rbuf8Filled] = c;
++rbuf8Filled;
if (stride(rbuf8[]) == rbuf8Filled) // sequence is complete
{
char[] str = rbuf8[0 .. rbuf8Filled];
immutable dchar d = decodeFront(str);
wchar_t[4 / wchar_t.sizeof] wbuf;
immutable size = encode(wbuf, d);
foreach (i; 0 .. size)
trustedFPUTWC(wbuf[i], handle_);
rbuf8Filled = 0;
}
}
}
else static if (c.sizeof == 2)
{
import std.utf : decode;
if (c <= 0x7F)
{
highSurrogateShouldBeEmpty();
if (orientation_ <= 0) trustedFPUTC(c, handle_);
else trustedFPUTWC(c, handle_);
}
else if (0xD800 <= c && c <= 0xDBFF) // high surrogate
{
highSurrogateShouldBeEmpty();
highSurrogate = c;
}
else // standalone or low surrogate
{
dchar d = c;
if (highSurrogate != '\0')
{
immutable wchar[2] rbuf = [highSurrogate, c];
size_t index = 0;
d = decode(rbuf[], index);
highSurrogate = 0;
}
if (orientation_ <= 0)
{
char[4] wbuf;
immutable size = encode(wbuf, d);
foreach (i; 0 .. size)
trustedFPUTC(wbuf[i], handle_);
}
else
{
wchar_t[4 / wchar_t.sizeof] wbuf;
immutable size = encode(wbuf, d);
foreach (i; 0 .. size)
trustedFPUTWC(wbuf[i], handle_);
}
rbuf8Filled = 0;
}
}
else // 32-bit characters
{
import std.utf : encode;
highSurrogateShouldBeEmpty();
if (orientation_ <= 0)
{
if (c <= 0x7F)
{
trustedFPUTC(c, handle_);
}
else
{
char[4] buf = void;
immutable len = encode(buf, c);
foreach (i ; 0 .. len)
trustedFPUTC(buf[i], handle_);
}
}
else
{
version (Windows)
{
import std.utf : isValidDchar;
assert(isValidDchar(c));
if (c <= 0xFFFF)
{
trustedFPUTWC(cast(wchar_t) c, handle_);
}
else
{
trustedFPUTWC(cast(wchar_t)
((((c - 0x10000) >> 10) & 0x3FF)
+ 0xD800), handle_);
trustedFPUTWC(cast(wchar_t)
(((c - 0x10000) & 0x3FF) + 0xDC00),
handle_);
}
}
else version (Posix)
{
trustedFPUTWC(cast(wchar_t) c, handle_);
}
else
{
static assert(0);
}
}
}
}
}
/**
* Output range which locks the file when created, and unlocks the file when it goes
* out of scope.
*
* Returns: An $(REF_ALTTEXT output range, isOutputRange, std, range, primitives)
* which accepts string types, `ubyte[]`, individual character types, and
* individual `ubyte`s.
*
* Note: Writing either arrays of `char`s or `ubyte`s is faster than
* writing each character individually from a range. For large amounts of data,
* writing the contents in chunks using an intermediary array can result
* in a speed increase.
*
* Throws: $(REF UTFException, std, utf) if the data given is a `char` range
* and it contains malformed UTF data.
*
* See_Also: $(LREF byChunk) for an example.
*/
auto lockingTextWriter() @safe
{
return LockingTextWriter(this);
}
// An output range which optionally locks the file and puts it into
// binary mode (similar to rawWrite). Because it needs to restore
// the file mode on destruction, it is RefCounted on Windows.
struct BinaryWriterImpl(bool locking)
{
import std.traits : hasIndirections;
private:
// Access the FILE* handle through the 'file_' member
// to keep the object alive through refcounting
File file_;
string name;
version (Windows)
{
fileno_t fd;
int oldMode;
}
public:
// Don't use this, but `File.lockingBinaryWriter()` instead.
// Must be public for RefCounted and emplace() in druntime.
this(scope ref File f)
{
import std.exception : enforce;
file_ = f;
enforce(f._p && f._p.handle);
name = f._name;
FILE* fps = f._p.handle;
static if (locking)
_FLOCK(fps);
version (Windows)
{
.fflush(fps); // before changing translation mode
fd = .fileno(fps);
oldMode = ._setmode(fd, _O_BINARY);
}
}
~this()
{
if (!file_._p || !file_._p.handle)
return;
FILE* fps = file_._p.handle;
version (Windows)
{
.fflush(fps); // before restoring translation mode
._setmode(fd, oldMode);
}
_FUNLOCK(fps);
}
void rawWrite(T)(in T[] buffer)
{
import std.conv : text;
import std.exception : errnoEnforce;
auto result = trustedFwrite(file_._p.handle, buffer);
if (result == result.max) result = 0;
errnoEnforce(result == buffer.length,
text("Wrote ", result, " instead of ", buffer.length,
" objects of type ", T.stringof, " to file `",
name, "'"));
}
version (Windows)
{
@disable this(this);
}
else
{
this(this)
{
if (auto p = file_._p)
{
if (p.handle) _FLOCK(p.handle);
}
}
}
void put(T)(auto ref scope const T value)
if (!hasIndirections!T &&
!isInputRange!T)
{
rawWrite((&value)[0 .. 1]);
}
void put(T)(scope const(T)[] array)
if (!hasIndirections!T &&
!isInputRange!T)
{
rawWrite(array);
}
}
/** Returns an output range that locks the file and allows fast writing to it.
Example:
Produce a grayscale image of the $(LINK2 https://en.wikipedia.org/wiki/Mandelbrot_set, Mandelbrot set)
in binary $(LINK2 https://en.wikipedia.org/wiki/Netpbm_format, Netpbm format) to standard output.
---
import std.algorithm, std.complex, std.range, std.stdio;
void main()
{
enum size = 500;
writef("P5\n%d %d %d\n", size, size, ubyte.max);
iota(-1, 3, 2.0/size).map!(y =>
iota(-1.5, 0.5, 2.0/size).map!(x =>
cast(ubyte)(1+
recurrence!((a, n) => x + y * complex(0, 1) + a[n-1]^^2)(complex(0))
.take(ubyte.max)
.countUntil!(z => z.re^^2 + z.im^^2 > 4))
)
)
.copy(stdout.lockingBinaryWriter);
}
---
*/
auto lockingBinaryWriter()
{
alias LockingBinaryWriterImpl = BinaryWriterImpl!true;
version (Windows)
{
import std.typecons : RefCounted;
alias LockingBinaryWriter = RefCounted!LockingBinaryWriterImpl;
}
else
alias LockingBinaryWriter = LockingBinaryWriterImpl;
return LockingBinaryWriter(this);
}
@system unittest
{
import std.algorithm.mutation : reverse;
import std.exception : collectException;
static import std.file;
import std.range : only, retro;
import std.string : format;
auto deleteme = testFilename();
scope(exit) collectException(std.file.remove(deleteme));
{
auto writer = File(deleteme, "wb").lockingBinaryWriter();
auto input = File(deleteme, "rb");
ubyte[1] byteIn = [42];
writer.rawWrite(byteIn);
destroy(writer);
ubyte[1] byteOut = input.rawRead(new ubyte[1]);
assert(byteIn[0] == byteOut[0]);
}
auto output = File(deleteme, "wb");
auto writer = output.lockingBinaryWriter();
auto input = File(deleteme, "rb");
T[] readExact(T)(T[] buf)
{
auto result = input.rawRead(buf);
assert(result.length == buf.length,
"Read %d out of %d bytes"
.format(result.length, buf.length));
return result;
}
// test raw values
ubyte byteIn = 42;
byteIn.only.copy(writer); output.flush();
ubyte byteOut = readExact(new ubyte[1])[0];
assert(byteIn == byteOut);
// test arrays
ubyte[] bytesIn = [1, 2, 3, 4, 5];
bytesIn.copy(writer); output.flush();
ubyte[] bytesOut = readExact(new ubyte[bytesIn.length]);
scope(failure) .writeln(bytesOut);
assert(bytesIn == bytesOut);
// test ranges of values
bytesIn.retro.copy(writer); output.flush();
bytesOut = readExact(bytesOut);
bytesOut.reverse();
assert(bytesIn == bytesOut);
// test string
"foobar".copy(writer); output.flush();
char[] charsOut = readExact(new char[6]);
assert(charsOut == "foobar");
// test ranges of arrays
only("foo", "bar").copy(writer); output.flush();
charsOut = readExact(charsOut);
assert(charsOut == "foobar");
// test that we are writing arrays as is,
// without UTF-8 transcoding
"foo"d.copy(writer); output.flush();
dchar[] dcharsOut = readExact(new dchar[3]);
assert(dcharsOut == "foo");
}
/** Returns the size of the file in bytes, ulong.max if file is not searchable or throws if the operation fails.
Example:
---
import std.stdio, std.file;
void main()
{
string deleteme = "delete.me";
auto file_handle = File(deleteme, "w");
file_handle.write("abc"); //create temporary file
scope(exit) deleteme.remove; //remove temporary file at scope exit
assert(file_handle.size() == 3); //check if file size is 3 bytes
}
---
*/
@property ulong size() @safe
{
import std.exception : collectException;
ulong pos = void;
if (collectException(pos = tell)) return ulong.max;
scope(exit) seek(pos);
seek(0, SEEK_END);
return tell;
}
}
@system unittest
{
@system struct SystemToString
{
string toString()
{
return "system";
}
}
@trusted struct TrustedToString
{
string toString()
{
return "trusted";
}
}
@safe struct SafeToString
{
string toString()
{
return "safe";
}
}
@system void systemTests()
{
//system code can write to files/stdout with anything!
if (false)
{
auto f = File();
f.write("just a string");
f.write("string with arg: ", 47);
f.write(SystemToString());
f.write(TrustedToString());
f.write(SafeToString());
write("just a string");
write("string with arg: ", 47);
write(SystemToString());
write(TrustedToString());
write(SafeToString());
f.writeln("just a string");
f.writeln("string with arg: ", 47);
f.writeln(SystemToString());
f.writeln(TrustedToString());
f.writeln(SafeToString());
writeln("just a string");
writeln("string with arg: ", 47);
writeln(SystemToString());
writeln(TrustedToString());
writeln(SafeToString());
f.writef("string with arg: %s", 47);
f.writef("%s", SystemToString());
f.writef("%s", TrustedToString());
f.writef("%s", SafeToString());
writef("string with arg: %s", 47);
writef("%s", SystemToString());
writef("%s", TrustedToString());
writef("%s", SafeToString());
f.writefln("string with arg: %s", 47);
f.writefln("%s", SystemToString());
f.writefln("%s", TrustedToString());
f.writefln("%s", SafeToString());
writefln("string with arg: %s", 47);
writefln("%s", SystemToString());
writefln("%s", TrustedToString());
writefln("%s", SafeToString());
}
}
@safe void safeTests()
{
auto f = File();
//safe code can write to files only with @safe and @trusted code...
if (false)
{
f.write("just a string");
f.write("string with arg: ", 47);
f.write(TrustedToString());
f.write(SafeToString());
write("just a string");
write("string with arg: ", 47);
write(TrustedToString());
write(SafeToString());
f.writeln("just a string");
f.writeln("string with arg: ", 47);
f.writeln(TrustedToString());
f.writeln(SafeToString());
writeln("just a string");
writeln("string with arg: ", 47);
writeln(TrustedToString());
writeln(SafeToString());
f.writef("string with arg: %s", 47);
f.writef("%s", TrustedToString());
f.writef("%s", SafeToString());
writef("string with arg: %s", 47);
writef("%s", TrustedToString());
writef("%s", SafeToString());
f.writefln("string with arg: %s", 47);
f.writefln("%s", TrustedToString());
f.writefln("%s", SafeToString());
writefln("string with arg: %s", 47);
writefln("%s", TrustedToString());
writefln("%s", SafeToString());
}
static assert(!__traits(compiles, f.write(SystemToString().toString())));
static assert(!__traits(compiles, f.writeln(SystemToString())));
static assert(!__traits(compiles, f.writef("%s", SystemToString())));
static assert(!__traits(compiles, f.writefln("%s", SystemToString())));
static assert(!__traits(compiles, write(SystemToString().toString())));
static assert(!__traits(compiles, writeln(SystemToString())));
static assert(!__traits(compiles, writef("%s", SystemToString())));
static assert(!__traits(compiles, writefln("%s", SystemToString())));
}
systemTests();
safeTests();
}
@safe unittest
{
import std.exception : collectException;
static import std.file;
auto deleteme = testFilename();
scope(exit) collectException(std.file.remove(deleteme));
std.file.write(deleteme, "1 2 3");
auto f = File(deleteme);
assert(f.size == 5);
assert(f.tell == 0);
}
@safe unittest
{
static import std.file;
import std.range : chain, only, repeat;
import std.range.primitives : isOutputRange;
auto deleteme = testFilename();
scope(exit) std.file.remove(deleteme);
{
auto writer = File(deleteme, "w").lockingTextWriter();
static assert(isOutputRange!(typeof(writer), dchar));
writer.put("日本語");
writer.put("日本語"w);
writer.put("日本語"d);
writer.put('日');
writer.put(chain(only('本'), only('語')));
// https://issues.dlang.org/show_bug.cgi?id=11945
writer.put(repeat('#', 12));
// https://issues.dlang.org/show_bug.cgi?id=17229
writer.put(cast(immutable(ubyte)[])"日本語");
}
assert(File(deleteme).readln() == "日本語日本語日本語日本語############日本語");
}
@safe unittest // wchar -> char
{
static import std.file;
import std.exception : assertThrown;
import std.utf : UTFException;
auto deleteme = testFilename();
scope(exit) std.file.remove(deleteme);
{
auto writer = File(deleteme, "w").lockingTextWriter();
writer.put("\U0001F608"w);
}
assert(std.file.readText!string(deleteme) == "\U0001F608");
// Test invalid input: unpaired high surrogate
{
immutable wchar surr = "\U0001F608"w[0];
auto f = File(deleteme, "w");
assertThrown!UTFException(() {
auto writer = f.lockingTextWriter();
writer.put('x');
writer.put(surr);
assertThrown!UTFException(writer.put(char('y')));
assertThrown!UTFException(writer.put(wchar('y')));
assertThrown!UTFException(writer.put(dchar('y')));
assertThrown!UTFException(writer.put(surr));
// First `surr` is still unpaired at this point. `writer` gets
// destroyed now, and the destructor throws a UTFException for
// the unpaired surrogate.
} ());
}
assert(std.file.readText!string(deleteme) == "x");
// Test invalid input: unpaired low surrogate
{
immutable wchar surr = "\U0001F608"w[1];
auto writer = File(deleteme, "w").lockingTextWriter();
assertThrown!UTFException(writer.put(surr));
writer.put('y');
assertThrown!UTFException(writer.put(surr));
}
assert(std.file.readText!string(deleteme) == "y");
}
@safe unittest // https://issues.dlang.org/show_bug.cgi?id=18801
{
static import std.file;
import std.string : stripLeft;
auto deleteme = testFilename();
scope(exit) std.file.remove(deleteme);
{
auto writer = File(deleteme, "w,ccs=UTF-8").lockingTextWriter();
writer.put("foo");
}
assert(std.file.readText!string(deleteme).stripLeft("\uFEFF") == "foo");
{
auto writer = File(deleteme, "a,ccs=UTF-8").lockingTextWriter();
writer.put("bar");
}
assert(std.file.readText!string(deleteme).stripLeft("\uFEFF") == "foobar");
}
@safe unittest // char/wchar -> wchar_t
{
import core.stdc.locale : LC_CTYPE, setlocale;
import core.stdc.wchar_ : fwide;
import core.stdc.string : strlen;
import std.algorithm.searching : any, endsWith;
import std.conv : text;
import std.meta : AliasSeq;
import std.string : fromStringz, stripLeft;
static import std.file;
auto deleteme = testFilename();
scope(exit) std.file.remove(deleteme);
const char* oldCt = () @trusted {
const(char)* p = setlocale(LC_CTYPE, null);
// Subsequent calls to `setlocale` might invalidate this return value,
// so duplicate it.
// See: https://github.com/dlang/phobos/pull/7660
return p ? p[0 .. strlen(p) + 1].idup.ptr : null;
}();
const utf8 = ["en_US.UTF-8", "C.UTF-8", ".65001"].any!((loc) @trusted {
return setlocale(LC_CTYPE, loc.ptr).fromStringz.endsWith(loc);
});
scope(exit) () @trusted { setlocale(LC_CTYPE, oldCt); } ();
alias strs = AliasSeq!("xä\U0001F607", "yö\U0001F608"w);
{
auto f = File(deleteme, "w");
version (CRuntime_Microsoft)
{
() @trusted { _setmode(fileno(f.getFP()), _O_U8TEXT); } ();
}
else
{
assert(fwide(f.getFP(), 1) == 1);
}
auto writer = f.lockingTextWriter();
assert(writer.orientation_ == 1);
static foreach (s; strs) writer.put(s);
}
assert(std.file.readText!string(deleteme).stripLeft("\uFEFF") ==
text(strs));
}
@safe unittest // https://issues.dlang.org/show_bug.cgi?id=18789
{
static import std.file;
auto deleteme = testFilename();
scope(exit) std.file.remove(deleteme);
// converting to char
{
auto f = File(deleteme, "w");
f.writeln("\U0001F608"w); // UTFException
}
// converting to wchar_t
{
auto f = File(deleteme, "w,ccs=UTF-16LE");
// from char
f.writeln("ö"); // writes garbage
f.writeln("\U0001F608"); // ditto
// from wchar
f.writeln("\U0001F608"w); // leads to ErrnoException
}
}
@safe unittest
{
import std.exception : collectException;
auto e = collectException({ File f; f.writeln("Hello!"); }());
assert(e && e.msg == "Attempting to write to closed File");
}
@safe unittest // https://issues.dlang.org/show_bug.cgi?id=21592
{
import std.exception : collectException;
import std.utf : UTFException;
static import std.file;
auto deleteme = testFilename();
scope(exit) std.file.remove(deleteme);
auto f = File(deleteme, "w");
auto e = collectException!UTFException(f.writeln(wchar(0xD801)));
assert(e.next is null);
}
version (StdStressTest)
{
// https://issues.dlang.org/show_bug.cgi?id=15768
@system unittest
{
import std.parallelism : parallel;
import std.range : iota;
auto deleteme = testFilename();
stderr = File(deleteme, "w");
foreach (t; 1_000_000.iota.parallel)
{
stderr.write("aaa");
}
}
}
/// Used to specify the lock type for `File.lock` and `File.tryLock`.
enum LockType
{
/**
* Specifies a _read (shared) lock. A _read lock denies all processes
* write access to the specified region of the file, including the
* process that first locks the region. All processes can _read the
* locked region. Multiple simultaneous _read locks are allowed, as
* long as there are no exclusive locks.
*/
read,
/**
* Specifies a read/write (exclusive) lock. A read/write lock denies all
* other processes both read and write access to the locked file region.
* If a segment has an exclusive lock, it may not have any shared locks
* or other exclusive locks.
*/
readWrite
}
struct LockingTextReader
{
private File _f;
private char _front;
private bool _hasChar;
this(File f)
{
import std.exception : enforce;
enforce(f.isOpen, "LockingTextReader: File must be open");
_f = f;
_FLOCK(_f._p.handle);
}
this(this)
{
_FLOCK(_f._p.handle);
}
~this()
{
if (_hasChar)
ungetc(_front, cast(FILE*)_f._p.handle);
// File locking has its own reference count
if (_f.isOpen) _FUNLOCK(_f._p.handle);
}
void opAssign(LockingTextReader r)
{
import std.algorithm.mutation : swap;
swap(this, r);
}
@property bool empty()
{
if (!_hasChar)
{
if (!_f.isOpen || _f.eof)
return true;
immutable int c = _FGETC(cast(_iobuf*) _f._p.handle);
if (c == EOF)
{
.destroy(_f);
return true;
}
_front = cast(char) c;
_hasChar = true;
}
return false;
}
@property char front()
{
if (!_hasChar)
{
version (assert)
{
import core.exception : RangeError;
if (empty)
throw new RangeError();
}
else
{
empty;
}
}
return _front;
}
void popFront()
{
if (!_hasChar)
empty;
_hasChar = false;
}
}
@system unittest
{
// @system due to readf
static import std.file;
import std.range.primitives : isInputRange;
static assert(isInputRange!LockingTextReader);
auto deleteme = testFilename();
std.file.write(deleteme, "1 2 3");
scope(exit) std.file.remove(deleteme);
int x;
auto f = File(deleteme);
f.readf("%s ", &x);
assert(x == 1);
f.readf("%d ", &x);
assert(x == 2);
f.readf("%d ", &x);
assert(x == 3);
}
// https://issues.dlang.org/show_bug.cgi?id=13686
@system unittest
{
import std.algorithm.comparison : equal;
static import std.file;
import std.utf : byDchar;
auto deleteme = testFilename();
std.file.write(deleteme, "Тест");
scope(exit) std.file.remove(deleteme);
string s;
File(deleteme).readf("%s", &s);
assert(s == "Тест");
auto ltr = LockingTextReader(File(deleteme)).byDchar;
assert(equal(ltr, "Тест".byDchar));
}
// https://issues.dlang.org/show_bug.cgi?id=12320
@system unittest
{
static import std.file;
auto deleteme = testFilename();
std.file.write(deleteme, "ab");
scope(exit) std.file.remove(deleteme);
auto ltr = LockingTextReader(File(deleteme));
assert(ltr.front == 'a');
ltr.popFront();
assert(ltr.front == 'b');
ltr.popFront();
assert(ltr.empty);
}
// https://issues.dlang.org/show_bug.cgi?id=14861
@system unittest
{
// @system due to readf
static import std.file;
auto deleteme = testFilename();
File fw = File(deleteme, "w");
for (int i; i != 5000; i++)
fw.writeln(i, ";", "Иванов;Пётр;Петрович");
fw.close();
scope(exit) std.file.remove(deleteme);
// Test read
File fr = File(deleteme, "r");
scope (exit) fr.close();
int nom; string fam, nam, ot;
// Error format read
while (!fr.eof)
fr.readf("%s;%s;%s;%s\n", &nom, &fam, &nam, &ot);
}
/**
* Indicates whether `T` is a file handle, i.e. the type
* is implicitly convertable to $(LREF File) or a pointer to a
* $(REF FILE, core,stdc,stdio).
*
* Returns:
* `true` if `T` is a file handle, `false` otherwise.
*/
template isFileHandle(T)
{
enum isFileHandle = is(T : FILE*) ||
is(T : File);
}
///
@safe unittest
{
static assert(isFileHandle!(FILE*));
static assert(isFileHandle!(File));
}
/**
* Property used by writeln/etc. so it can infer @safe since stdout is __gshared
*/
private @property File trustedStdout() @trusted
{
return stdout;
}
/***********************************
Writes its arguments in text format to standard output (without a trailing newline).
Params:
args = the items to write to `stdout`
Throws: In case of an I/O error, throws an `StdioException`.
Example:
Reads `stdin` and writes it to `stdout` with an argument
counter.
---
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
write("Input ", count, ": ", line, "\n");
}
}
---
*/
void write(T...)(T args)
if (!is(T[0] : File))
{
trustedStdout.write(args);
}
@system unittest
{
static import std.file;
scope(failure) printf("Failed test at line %d\n", __LINE__);
void[] buf;
if (false) write(buf);
// test write
auto deleteme = testFilename();
auto f = File(deleteme, "w");
f.write("Hello, ", "world number ", 42, "!");
f.close();
scope(exit) { std.file.remove(deleteme); }
assert(cast(char[]) std.file.read(deleteme) == "Hello, world number 42!");
}
/***********************************
* Equivalent to `write(args, '\n')`. Calling `writeln` without
* arguments is valid and just prints a newline to the standard
* output.
*
* Params:
* args = the items to write to `stdout`
*
* Throws:
* In case of an I/O error, throws an $(LREF StdioException).
* Example:
* Reads `stdin` and writes it to `stdout` with an argument
* counter.
---
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
---
*/
void writeln(T...)(T args)
{
static if (T.length == 0)
{
import std.exception : enforce;
enforce(fputc('\n', .trustedStdout._p.handle) != EOF, "fputc failed");
}
else static if (T.length == 1 &&
is(T[0] : const(char)[]) &&
(is(T[0] == U[], U) || __traits(isStaticArray, T[0])))
{
// Specialization for strings - a very frequent case
auto w = .trustedStdout.lockingTextWriter();
static if (__traits(isStaticArray, T[0]))
{
w.put(args[0][]);
}
else
{
w.put(args[0]);
}
w.put('\n');
}
else
{
// Most general instance
trustedStdout.write(args, '\n');
}
}
@safe unittest
{
// Just make sure the call compiles
if (false) writeln();
if (false) writeln("wyda");
// https://issues.dlang.org/show_bug.cgi?id=8040
if (false) writeln(null);
if (false) writeln(">", null, "<");
// https://issues.dlang.org/show_bug.cgi?id=14041
if (false)
{
char[8] a;
writeln(a);
immutable b = a;
b.writeln;
const c = a[];
c.writeln;
}
}
@system unittest
{
static import std.file;
scope(failure) printf("Failed test at line %d\n", __LINE__);
// test writeln
auto deleteme = testFilename();
auto f = File(deleteme, "w");
scope(exit) { std.file.remove(deleteme); }
f.writeln("Hello, ", "world number ", 42, "!");
f.close();
version (Windows)
assert(cast(char[]) std.file.read(deleteme) ==
"Hello, world number 42!\r\n");
else
assert(cast(char[]) std.file.read(deleteme) ==
"Hello, world number 42!\n");
// test writeln on stdout
auto saveStdout = stdout;
scope(exit) stdout = saveStdout;
stdout.open(deleteme, "w");
writeln("Hello, ", "world number ", 42, "!");
stdout.close();
version (Windows)
assert(cast(char[]) std.file.read(deleteme) ==
"Hello, world number 42!\r\n");
else
assert(cast(char[]) std.file.read(deleteme) ==
"Hello, world number 42!\n");
stdout.open(deleteme, "w");
writeln("Hello!"c);
writeln("Hello!"w); // https://issues.dlang.org/show_bug.cgi?id=8386
writeln("Hello!"d); // https://issues.dlang.org/show_bug.cgi?id=8386
writeln("embedded\0null"c); // https://issues.dlang.org/show_bug.cgi?id=8730
stdout.close();
version (Windows)
assert(cast(char[]) std.file.read(deleteme) ==
"Hello!\r\nHello!\r\nHello!\r\nembedded\0null\r\n");
else
assert(cast(char[]) std.file.read(deleteme) ==
"Hello!\nHello!\nHello!\nembedded\0null\n");
}
@system unittest
{
static import std.file;
auto deleteme = testFilename();
auto f = File(deleteme, "w");
scope(exit) { std.file.remove(deleteme); }
enum EI : int { A, B }
enum ED : double { A = 0, B } // NOTE: explicit initialization to 0 required during Enum init deprecation cycle
enum EC : char { A = 0, B } // NOTE: explicit initialization to 0 required during Enum init deprecation cycle
enum ES : string { A = "aaa", B = "bbb" }
f.writeln(EI.A); // false, but A on 2.058
f.writeln(EI.B); // true, but B on 2.058
f.writeln(ED.A); // A
f.writeln(ED.B); // B
f.writeln(EC.A); // A
f.writeln(EC.B); // B
f.writeln(ES.A); // A
f.writeln(ES.B); // B
f.close();
version (Windows)
assert(cast(char[]) std.file.read(deleteme) ==
"A\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\n");
else
assert(cast(char[]) std.file.read(deleteme) ==
"A\nB\nA\nB\nA\nB\nA\nB\n");
}
@system unittest
{
static auto useInit(T)(T ltw)
{
T val;
val = ltw;
val = T.init;
return val;
}
useInit(stdout.lockingTextWriter());
}
@system unittest
{
// https://issues.dlang.org/show_bug.cgi?id=21920
void function(string) printer = &writeln!string;
if (false) printer("Hello");
}
/***********************************
Writes formatted data to standard output (without a trailing newline).
Params:
fmt = The $(REF_ALTTEXT format string, formattedWrite, std, _format).
When passed as a compile-time argument, the string will be statically checked
against the argument types passed.
args = Items to write.
Note: In older versions of Phobos, it used to be possible to write:
------
writef(stderr, "%s", "message");
------
to print a message to `stderr`. This syntax is no longer supported, and has
been superceded by:
------
stderr.writef("%s", "message");
------
*/
void writef(alias fmt, A...)(A args)
if (isSomeString!(typeof(fmt)))
{
import std.format : checkFormatException;
alias e = checkFormatException!(fmt, A);
static assert(!e, e);
return .writef(fmt, args);
}
/// ditto
void writef(Char, A...)(in Char[] fmt, A args)
{
trustedStdout.writef(fmt, args);
}
@system unittest
{
static import std.file;
scope(failure) printf("Failed test at line %d\n", __LINE__);
// test writef
auto deleteme = testFilename();
auto f = File(deleteme, "w");
scope(exit) { std.file.remove(deleteme); }
f.writef!"Hello, %s world number %s!"("nice", 42);
f.close();
assert(cast(char[]) std.file.read(deleteme) == "Hello, nice world number 42!");
// test write on stdout
auto saveStdout = stdout;
scope(exit) stdout = saveStdout;
stdout.open(deleteme, "w");
writef!"Hello, %s world number %s!"("nice", 42);
stdout.close();
assert(cast(char[]) std.file.read(deleteme) == "Hello, nice world number 42!");
}
/***********************************
* Equivalent to $(D writef(fmt, args, '\n')).
*/
void writefln(alias fmt, A...)(A args)
if (isSomeString!(typeof(fmt)))
{
import std.format : checkFormatException;
alias e = checkFormatException!(fmt, A);
static assert(!e, e);
return .writefln(fmt, args);
}
/// ditto
void writefln(Char, A...)(in Char[] fmt, A args)
{
trustedStdout.writefln(fmt, args);
}
@system unittest
{
static import std.file;
scope(failure) printf("Failed test at line %d\n", __LINE__);
// test File.writefln
auto deleteme = testFilename();
auto f = File(deleteme, "w");
scope(exit) { std.file.remove(deleteme); }
f.writefln!"Hello, %s world number %s!"("nice", 42);
f.close();
version (Windows)
assert(cast(char[]) std.file.read(deleteme) ==
"Hello, nice world number 42!\r\n");
else
assert(cast(char[]) std.file.read(deleteme) ==
"Hello, nice world number 42!\n",
cast(char[]) std.file.read(deleteme));
// test writefln
auto saveStdout = stdout;
scope(exit) stdout = saveStdout;
stdout.open(deleteme, "w");
writefln!"Hello, %s world number %s!"("nice", 42);
stdout.close();
version (Windows)
assert(cast(char[]) std.file.read(deleteme) ==
"Hello, nice world number 42!\r\n");
else
assert(cast(char[]) std.file.read(deleteme) ==
"Hello, nice world number 42!\n");
}
/**
* Reads formatted data from `stdin` using $(REF formattedRead, std,_format).
* Params:
* format = The $(REF_ALTTEXT format string, formattedWrite, std, _format).
* When passed as a compile-time argument, the string will be statically checked
* against the argument types passed.
* args = Items to be read.
* Returns:
* Same as `formattedRead`: The number of variables filled. If the input range `r` ends early,
* this number will be less than the number of variables provided.
* Example:
----
// test.d
void main()
{
import std.stdio;
foreach (_; 0 .. 3)
{
int a;
readf!" %d"(a);
writeln(++a);
}
}
----
$(CONSOLE
% echo "1 2 3" | rdmd test.d
2
3
4
)
*/
uint readf(alias format, A...)(auto ref A args)
if (isSomeString!(typeof(format)))
{
import std.format : checkFormatException;
alias e = checkFormatException!(format, A);
static assert(!e, e);
return .readf(format, args);
}
/// ditto
uint readf(A...)(scope const(char)[] format, auto ref A args)
{
return stdin.readf(format, args);
}
@system unittest
{
float f;
if (false) readf("%s", &f);
char a;
wchar b;
dchar c;
if (false) readf("%s %s %s", a, b, c);
// backwards compatibility with pointers
if (false) readf("%s %s %s", a, &b, c);
if (false) readf("%s %s %s", &a, &b, &c);
}
/**********************************
* Read line from `stdin`.
*
* This version manages its own read buffer, which means one memory allocation per call. If you are not
* retaining a reference to the read data, consider the `readln(buf)` version, which may offer
* better performance as it can reuse its read buffer.
*
* Returns:
* The line that was read, including the line terminator character.
* Params:
* S = Template parameter; the type of the allocated buffer, and the type returned. Defaults to `string`.
* terminator = Line terminator (by default, `'\n'`).
* Note:
* String terminators are not supported due to ambiguity with readln(buf) below.
* Throws:
* `StdioException` on I/O error, or `UnicodeException` on Unicode conversion error.
* Example:
* Reads `stdin` and writes it to `stdout`.
---
import std.stdio;
void main()
{
string line;
while ((line = readln()) !is null)
write(line);
}
---
*/
S readln(S = string)(dchar terminator = '\n')
if (isSomeString!S)
{
return stdin.readln!S(terminator);
}
/**********************************
* Read line from `stdin` and write it to buf[], including terminating character.
*
* This can be faster than $(D line = readln()) because you can reuse
* the buffer for each call. Note that reusing the buffer means that you
* must copy the previous contents if you wish to retain them.
*
* Returns:
* `size_t` 0 for end of file, otherwise number of characters read
* Params:
* buf = Buffer used to store the resulting line data. buf is resized as necessary.
* terminator = Line terminator (by default, `'\n'`). Use $(REF newline, std,ascii)
* for portability (unless the file was opened in text mode).
* Throws:
* `StdioException` on I/O error, or `UnicodeException` on Unicode conversion error.
* Example:
* Reads `stdin` and writes it to `stdout`.
---
import std.stdio;
void main()
{
char[] buf;
while (readln(buf))
write(buf);
}
---
*/
size_t readln(C)(ref C[] buf, dchar terminator = '\n')
if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum))
{
return stdin.readln(buf, terminator);
}
/** ditto */
size_t readln(C, R)(ref C[] buf, R terminator)
if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum) &&
isBidirectionalRange!R && is(typeof(terminator.front == dchar.init)))
{
return stdin.readln(buf, terminator);
}
@safe unittest
{
import std.meta : AliasSeq;
//we can't actually test readln, so at the very least,
//we test compilability
void foo()
{
readln();
readln('\t');
static foreach (String; AliasSeq!(string, char[], wstring, wchar[], dstring, dchar[]))
{
readln!String();
readln!String('\t');
}
static foreach (String; AliasSeq!(char[], wchar[], dchar[]))
{{
String buf;
readln(buf);
readln(buf, '\t');
readln(buf, "<br />");
}}
}
}
/**
Reads a line from `stdin` and parses it using $(REF formattedRead, std,format,read).
Params:
format = The $(MREF_ALTTEXT format string, std,format). When passed as a
compile-time argument, the string will be statically checked against the
argument types passed.
data = Items to be read.
Returns: Same as `formattedRead`: the number of variables filled. If the
input ends early, this number will be less that the number of variables
provided.
Example:
---
// sum_rows.d
void main()
{
import std.stdio;
int a, b, c;
while (readfln("%d %d %d", a, b, c) == 3)
{
writeln(a + b + c);
}
}
---
$(CONSOLE
% cat << EOF > input
1 2 3
4 5 6
7 8 9
EOF
% rdmd sum_rows.d < input
6
15
24
)
*/
uint readfln(alias format, Data...)(auto ref Data data)
{
import std.format : checkFormatException;
alias e = checkFormatException!(format, Data);
static assert(!e, e);
return .readfln(format, data);
}
/// ditto
uint readfln(Data...)(scope const(char)[] format, auto ref Data data)
{
return stdin.readfln(format, data);
}
@system unittest
{
float f;
string s;
char c;
int n;
if (false) readfln("%f %s %c %d", f, s, c, n);
if (false) readfln!"%f %s %c %d"(f, s, c, n);
}
/*
* Convenience function that forwards to `core.sys.posix.stdio.fopen`
* (to `_wfopen` on Windows)
* with appropriately-constructed C-style strings.
*/
private FILE* _fopen(R1, R2)(R1 name, R2 mode = "r")
if ((isSomeFiniteCharInputRange!R1 || isSomeString!R1) &&
(isSomeFiniteCharInputRange!R2 || isSomeString!R2))
{
import std.internal.cstring : tempCString;
auto namez = name.tempCString!FSChar();
auto modez = mode.tempCString!FSChar();
static _fopenImpl(scope const(FSChar)* namez, scope const(FSChar)* modez) @trusted nothrow @nogc
{
version (Windows)
{
return _wfopen(namez, modez);
}
else version (Posix)
{
/*
* The new opengroup large file support API is transparently
* included in the normal C bindings. https://www.opengroup.org/platform/lfs.html#1.0
* if _FILE_OFFSET_BITS in druntime is 64, off_t is 64 bit and
* the normal functions work fine. If not, then large file support
* probably isn't available. Do not use the old transitional API
* (the native extern(C) fopen64, https://unix.org/version2/whatsnew/lfs20mar.html#3.0)
*/
import core.sys.posix.stdio : fopen;
return fopen(namez, modez);
}
else
{
return fopen(namez, modez);
}
}
return _fopenImpl(namez, modez);
}
version (Posix)
{
/***********************************
* Convenience function that forwards to `core.sys.posix.stdio.popen`
* with appropriately-constructed C-style strings.
*/
FILE* _popen(R1, R2)(R1 name, R2 mode = "r") @trusted nothrow @nogc
if ((isSomeFiniteCharInputRange!R1 || isSomeString!R1) &&
(isSomeFiniteCharInputRange!R2 || isSomeString!R2))
{
import std.internal.cstring : tempCString;
auto namez = name.tempCString!FSChar();
auto modez = mode.tempCString!FSChar();
static popenImpl(const(FSChar)* namez, const(FSChar)* modez) @trusted nothrow @nogc
{
import core.sys.posix.stdio : popen;
return popen(namez, modez);
}
return popenImpl(namez, modez);
}
}
/*
* Convenience function that forwards to `core.stdc.stdio.fwrite`
*/
private auto trustedFwrite(T)(FILE* f, const T[] obj) @trusted
{
return fwrite(obj.ptr, T.sizeof, obj.length, f);
}
/*
* Convenience function that forwards to `core.stdc.stdio.fread`
*/
private auto trustedFread(T)(FILE* f, T[] obj) @trusted
if (!imported!"std.traits".hasIndirections!T)
{
return fread(obj.ptr, T.sizeof, obj.length, f);
}
private auto trustedFread(T)(FILE* f, T[] obj) @system
if (imported!"std.traits".hasIndirections!T)
{
return fread(obj.ptr, T.sizeof, obj.length, f);
}
/**
* Iterates through the lines of a file by using `foreach`.
*
* Example:
*
---------
void main()
{
foreach (string line; lines(stdin))
{
... use line ...
}
}
---------
The line terminator (`'\n'` by default) is part of the string read (it
could be missing in the last line of the file). Several types are
supported for `line`, and the behavior of `lines`
changes accordingly:
$(OL $(LI If `line` has type `string`, $(D
wstring), or `dstring`, a new string of the respective type
is allocated every read.) $(LI If `line` has type $(D
char[]), `wchar[]`, `dchar[]`, the line's content
will be reused (overwritten) across reads.) $(LI If `line`
has type `immutable(ubyte)[]`, the behavior is similar to
case (1), except that no UTF checking is attempted upon input.) $(LI
If `line` has type `ubyte[]`, the behavior is
similar to case (2), except that no UTF checking is attempted upon
input.))
In all cases, a two-symbols versions is also accepted, in which case
the first symbol (of integral type, e.g. `ulong` or $(D
uint)) tracks the zero-based number of the current line.
Example:
----
foreach (ulong i, string line; lines(stdin))
{
... use line ...
}
----
In case of an I/O error, an `StdioException` is thrown.
See_Also:
$(LREF byLine)
*/
struct lines
{
private File f;
private dchar terminator = '\n';
/**
Constructor.
Params:
f = File to read lines from.
terminator = Line separator (`'\n'` by default).
*/
this(File f, dchar terminator = '\n') @safe
{
this.f = f;
this.terminator = terminator;
}
int opApply(D)(scope D dg)
{
import std.traits : Parameters;
alias Parms = Parameters!(dg);
static if (isSomeString!(Parms[$ - 1]))
{
int result = 0;
static if (is(Parms[$ - 1] : const(char)[]))
alias C = char;
else static if (is(Parms[$ - 1] : const(wchar)[]))
alias C = wchar;
else static if (is(Parms[$ - 1] : const(dchar)[]))
alias C = dchar;
C[] line;
static if (Parms.length == 2)
Parms[0] i = 0;
for (;;)
{
import std.conv : to;
if (!f.readln(line, terminator)) break;
auto copy = to!(Parms[$ - 1])(line);
static if (Parms.length == 2)
{
result = dg(i, copy);
++i;
}
else
{
result = dg(copy);
}
if (result != 0) break;
}
return result;
}
else
{
// raw read
return opApplyRaw(dg);
}
}
// no UTF checking
int opApplyRaw(D)(scope D dg)
{
import std.conv : to;
import std.exception : assumeUnique;
import std.traits : Parameters;
alias Parms = Parameters!(dg);
enum duplicate = is(Parms[$ - 1] : immutable(ubyte)[]);
int result = 1;
int c = void;
_FLOCK(f._p.handle);
scope(exit) _FUNLOCK(f._p.handle);
ubyte[] buffer;
static if (Parms.length == 2)
Parms[0] line = 0;
while ((c = _FGETC(cast(_iobuf*) f._p.handle)) != -1)
{
buffer ~= to!(ubyte)(c);
if (c == terminator)
{
static if (duplicate)
auto arg = assumeUnique(buffer);
else
alias arg = buffer;
// unlock the file while calling the delegate
_FUNLOCK(f._p.handle);
scope(exit) _FLOCK(f._p.handle);
static if (Parms.length == 1)
{
result = dg(arg);
}
else
{
result = dg(line, arg);
++line;
}
if (result) break;
static if (!duplicate)
buffer.length = 0;
}
}
// can only reach when _FGETC returned -1
if (!f.eof) throw new StdioException("Error in reading file"); // error occured
return result;
}
}
@safe unittest
{
/*
As pointed out in <https://github.com/dlang/phobos/issues/10605>,
it's a pity that `byLine()` & co. aren't @safe to use yet.
This is a first attempt at working towards that goal.
For now, this test doesn't do much; as there isn't much to do safely yet.
*/
auto deleteMe = testFilename();
scope(exit) { imported!"std.file".remove(deleteMe); }
// Setup
{
auto f = File(deleteMe, "w");
scope(exit) { f.close(); }
foreach (i; 1 .. 11)
f.writeln(i);
}
// Actual tests
{
auto f = File(deleteMe, "r");
scope(exit) { f.close(); }
auto myLines = lines(f);
foreach (string line; myLines)
continue;
}
{
auto f = File(deleteMe, "r");
scope(exit) { f.close(); }
auto myByLineCopy = f.byLineCopy;
foreach (line; myByLineCopy)
continue;
}
{
auto f = File(deleteMe, "r");
scope(exit) { f.close(); }
auto myByLine = f.byLine;
foreach (line; myByLine)
continue;
}
}
@system unittest
{
static import std.file;
import std.meta : AliasSeq;
scope(failure) printf("Failed test at line %d\n", __LINE__);
auto deleteme = testFilename();
scope(exit) { std.file.remove(deleteme); }
alias TestedWith =
AliasSeq!(string, wstring, dstring,
char[], wchar[], dchar[]);
foreach (T; TestedWith)
{
// test looping with an empty file
std.file.write(deleteme, "");
auto f = File(deleteme, "r");
foreach (T line; lines(f))
{
assert(false);
}
f.close();
// test looping with a file with three lines
std.file.write(deleteme, "Line one\nline two\nline three\n");
f.open(deleteme, "r");
uint i = 0;
foreach (T line; lines(f))
{
if (i == 0) assert(line == "Line one\n");
else if (i == 1) assert(line == "line two\n");
else if (i == 2) assert(line == "line three\n");
else assert(false);
++i;
}
f.close();
// test looping with a file with three lines, last without a newline
std.file.write(deleteme, "Line one\nline two\nline three");
f.open(deleteme, "r");
i = 0;
foreach (T line; lines(f))
{
if (i == 0) assert(line == "Line one\n");
else if (i == 1) assert(line == "line two\n");
else if (i == 2) assert(line == "line three");
else assert(false);
++i;
}
f.close();
}
// test with ubyte[] inputs
alias TestedWith2 = AliasSeq!(immutable(ubyte)[], ubyte[]);
foreach (T; TestedWith2)
{
// test looping with an empty file
std.file.write(deleteme, "");
auto f = File(deleteme, "r");
foreach (T line; lines(f))
{
assert(false);
}
f.close();
// test looping with a file with three lines
std.file.write(deleteme, "Line one\nline two\nline three\n");
f.open(deleteme, "r");
uint i = 0;
foreach (T line; lines(f))
{
if (i == 0) assert(cast(char[]) line == "Line one\n");
else if (i == 1) assert(cast(char[]) line == "line two\n",
T.stringof ~ " " ~ cast(char[]) line);
else if (i == 2) assert(cast(char[]) line == "line three\n");
else assert(false);
++i;
}
f.close();
// test looping with a file with three lines, last without a newline
std.file.write(deleteme, "Line one\nline two\nline three");
f.open(deleteme, "r");
i = 0;
foreach (T line; lines(f))
{
if (i == 0) assert(cast(char[]) line == "Line one\n");
else if (i == 1) assert(cast(char[]) line == "line two\n");
else if (i == 2) assert(cast(char[]) line == "line three");
else assert(false);
++i;
}
f.close();
}
static foreach (T; AliasSeq!(ubyte[]))
{
// test looping with a file with three lines, last without a newline
// using a counter too this time
std.file.write(deleteme, "Line one\nline two\nline three");
auto f = File(deleteme, "r");
uint i = 0;
foreach (ulong j, T line; lines(f))
{
if (i == 0) assert(cast(char[]) line == "Line one\n");
else if (i == 1) assert(cast(char[]) line == "line two\n");
else if (i == 2) assert(cast(char[]) line == "line three");
else assert(false);
++i;
}
f.close();
}
}
/**
Iterates through a file a chunk at a time by using `foreach`.
Example:
---------
void main()
{
foreach (ubyte[] buffer; chunks(stdin, 4096))
{
... use buffer ...
}
}
---------
The content of `buffer` is reused across calls. In the
example above, `buffer.length` is 4096 for all iterations,
except for the last one, in which case `buffer.length` may
be less than 4096 (but always greater than zero).
In case of an I/O error, an `StdioException` is thrown.
*/
auto chunks(File f, size_t size)
{
return ChunksImpl(f, size);
}
private struct ChunksImpl
{
private File f;
private size_t size;
// private string fileName; // Currently, no use
this(File f, size_t size)
in
{
assert(size, "size must be larger than 0");
}
do
{
this.f = f;
this.size = size;
}
int opApply(D)(scope D dg)
{
import core.stdc.stdlib : alloca;
import std.exception : enforce;
enforce(f.isOpen, "Attempting to read from an unopened file");
enum maxStackSize = 1024 * 16;
ubyte[] buffer = void;
if (size < maxStackSize)
buffer = (cast(ubyte*) alloca(size))[0 .. size];
else
buffer = new ubyte[size];
size_t r = void;
int result = 1;
uint tally = 0;
while ((r = trustedFread(f._p.handle, buffer)) > 0)
{
assert(r <= size);
if (r != size)
{
// error occured
if (!f.eof) throw new StdioException(null);
buffer.length = r;
}
static if (is(typeof(dg(tally, buffer))))
{
if ((result = dg(tally, buffer)) != 0) break;
}
else
{
if ((result = dg(buffer)) != 0) break;
}
++tally;
}
return result;
}
}
@system unittest
{
static import std.file;
scope(failure) printf("Failed test at line %d\n", __LINE__);
auto deleteme = testFilename();
scope(exit) { std.file.remove(deleteme); }
// test looping with an empty file
std.file.write(deleteme, "");
auto f = File(deleteme, "r");
foreach (ubyte[] line; chunks(f, 4))
{
assert(false);
}
f.close();
// test looping with a file with three lines
std.file.write(deleteme, "Line one\nline two\nline three\n");
f = File(deleteme, "r");
uint i = 0;
foreach (ubyte[] line; chunks(f, 3))
{
if (i == 0) assert(cast(char[]) line == "Lin");
else if (i == 1) assert(cast(char[]) line == "e o");
else if (i == 2) assert(cast(char[]) line == "ne\n");
else break;
++i;
}
f.close();
}
// Issue 21730 - null ptr dereferenced in ChunksImpl.opApply (SIGSEGV)
@system unittest
{
import std.exception : assertThrown;
static import std.file;
auto deleteme = testFilename();
scope(exit) { if (std.file.exists(deleteme)) std.file.remove(deleteme); }
auto err1 = File(deleteme, "w+x");
err1.close;
std.file.remove(deleteme);
assertThrown(() {foreach (ubyte[] buf; chunks(err1, 4096)) {}}());
}
/**
Writes an array or range to a file.
Shorthand for $(D data.copy(File(fileName, "wb").lockingBinaryWriter)).
Similar to $(REF write, std,file), strings are written as-is,
rather than encoded according to the `File`'s $(HTTP
en.cppreference.com/w/c/io#Narrow_and_wide_orientation,
orientation).
*/
void toFile(T)(T data, string fileName)
if (is(typeof(copy(data, stdout.lockingBinaryWriter))))
{
copy(data, File(fileName, "wb").lockingBinaryWriter);
}
@system unittest
{
static import std.file;
auto deleteme = testFilename();
scope(exit) { std.file.remove(deleteme); }
"Test".toFile(deleteme);
assert(std.file.readText(deleteme) == "Test");
}
/*********************
* Thrown if I/O errors happen.
*/
class StdioException : Exception
{
static import core.stdc.errno;
/// Operating system error code.
uint errno;
/**
Initialize with a message and an error code.
*/
this(string message, uint e = core.stdc.errno.errno) @trusted
{
import std.exception : errnoString;
errno = e;
auto sysmsg = errnoString(errno);
// If e is 0, we don't use the system error message. (The message
// is "Success", which is rather pointless for an exception.)
super(e == 0 ? message
: (message ? message ~ " (" ~ sysmsg ~ ")" : sysmsg));
}
/** Convenience functions that throw an `StdioException`. */
static void opCall(string msg) @safe
{
throw new StdioException(msg);
}
/// ditto
static void opCall() @safe
{
throw new StdioException(null, core.stdc.errno.errno);
}
}
enum StdFileHandle: string
{
stdin = "core.stdc.stdio.stdin",
stdout = "core.stdc.stdio.stdout",
stderr = "core.stdc.stdio.stderr",
}
// Undocumented but public because the std* handles are aliasing it.
@property ref File makeGlobal(StdFileHandle _iob)()
{
__gshared File.Impl impl;
__gshared File result;
// Use an inline spinlock to make sure the initializer is only run once.
// We assume there will be at most uint.max / 2 threads trying to initialize
// `handle` at once and steal the high bit to indicate that the globals have
// been initialized.
static shared uint spinlock;
import core.atomic : atomicLoad, atomicOp, MemoryOrder;
if (atomicLoad!(MemoryOrder.acq)(spinlock) <= uint.max / 2)
{
for (;;)
{
if (atomicLoad!(MemoryOrder.acq)(spinlock) > uint.max / 2)
break;
if (atomicOp!"+="(spinlock, 1) == 1)
{
with (StdFileHandle)
assert(_iob == stdin || _iob == stdout || _iob == stderr);
impl.handle = cast() mixin(_iob);
result._p = &impl;
atomicOp!"+="(spinlock, uint.max / 2);
break;
}
atomicOp!"-="(spinlock, 1);
}
}
return result;
}
/** The standard input stream.
Returns:
stdin as a $(LREF File).
Note:
The returned $(LREF File) wraps $(REF stdin,core,stdc,stdio), and
is therefore thread global. Reassigning `stdin` to a different
`File` must be done in a single-threaded or locked context in
order to avoid race conditions.
All reading from `stdin` automatically locks the file globally,
and will cause all other threads calling `read` to wait until
the lock is released.
*/
alias stdin = makeGlobal!(StdFileHandle.stdin);
///
@safe unittest
{
// Read stdin, sort lines, write to stdout
import std.algorithm.mutation : copy;
import std.algorithm.sorting : sort;
import std.array : array;
import std.typecons : Yes;
void main()
{
stdin // read from stdin
.byLineCopy(Yes.keepTerminator) // copying each line
.array() // convert to array of lines
.sort() // sort the lines
.copy( // copy output of .sort to an OutputRange
stdout.lockingTextWriter()); // the OutputRange
}
}
/**
The standard output stream.
Returns:
stdout as a $(LREF File).
Note:
The returned $(LREF File) wraps $(REF stdout,core,stdc,stdio), and
is therefore thread global. Reassigning `stdout` to a different
`File` must be done in a single-threaded or locked context in
order to avoid race conditions.
All writing to `stdout` automatically locks the file globally,
and will cause all other threads calling `write` to wait until
the lock is released.
*/
alias stdout = makeGlobal!(StdFileHandle.stdout);
///
@safe unittest
{
void main()
{
stdout.writeln("Write a message to stdout.");
}
}
///
@safe unittest
{
void main()
{
import std.algorithm.iteration : filter, map, sum;
import std.format : format;
import std.range : iota, tee;
int len;
const r = 6.iota
.filter!(a => a % 2) // 1 3 5
.map!(a => a * 2) // 2 6 10
.tee!(_ => stdout.writefln("len: %d", len++))
.sum;
assert(r == 18);
}
}
///
@safe unittest
{
void main()
{
import std.algorithm.mutation : copy;
import std.algorithm.iteration : map;
import std.format : format;
import std.range : iota;
10.iota
.map!(e => "N: %d".format(e))
.copy(stdout.lockingTextWriter()); // the OutputRange
}
}
/**
The standard error stream.
Returns:
stderr as a $(LREF File).
Note:
The returned $(LREF File) wraps $(REF stderr,core,stdc,stdio), and
is therefore thread global. Reassigning `stderr` to a different
`File` must be done in a single-threaded or locked context in
order to avoid race conditions.
All writing to `stderr` automatically locks the file globally,
and will cause all other threads calling `write` to wait until
the lock is released.
*/
alias stderr = makeGlobal!(StdFileHandle.stderr);
///
@safe unittest
{
void main()
{
stderr.writeln("Write a message to stderr.");
}
}
@system unittest
{
static import std.file;
import std.typecons : tuple;
scope(failure) printf("Failed test at line %d\n", __LINE__);
auto deleteme = testFilename();
std.file.write(deleteme, "1 2\n4 1\n5 100");
scope(exit) std.file.remove(deleteme);
{
File f = File(deleteme);
scope(exit) f.close();
auto t = [ tuple(1, 2), tuple(4, 1), tuple(5, 100) ];
uint i;
foreach (e; f.byRecord!(int, int)("%s %s"))
{
//writeln(e);
assert(e == t[i++]);
}
assert(i == 3);
}
}
@safe unittest
{
// Retain backwards compatibility
// https://issues.dlang.org/show_bug.cgi?id=17472
static assert(is(typeof(stdin) == File));
static assert(is(typeof(stdout) == File));
static assert(is(typeof(stderr) == File));
}
// roll our own appender, but with "safe" arrays
private struct ReadlnAppender
{
char[] buf;
size_t pos;
bool safeAppend = false;
void initialize(char[] b) @safe
{
buf = b;
pos = 0;
}
@property char[] data() @trusted
{
if (safeAppend)
assumeSafeAppend(buf.ptr[0 .. pos]);
return buf.ptr[0 .. pos];
}
bool reserveWithoutAllocating(size_t n)
{
if (buf.length >= pos + n) // buf is already large enough
return true;
immutable curCap = buf.capacity;
if (curCap >= pos + n)
{
buf.length = curCap;
/* Any extra capacity we end up not using can safely be claimed
by someone else. */
safeAppend = true;
return true;
}
return false;
}
void reserve(size_t n) @trusted
{
import core.stdc.string : memcpy;
if (!reserveWithoutAllocating(n))
{
size_t ncap = buf.length * 2 + 128 + n;
char[] nbuf = new char[ncap];
memcpy(nbuf.ptr, buf.ptr, pos);
buf = nbuf;
// Allocated a new buffer. No one else knows about it.
safeAppend = true;
}
}
void putchar(char c) @trusted
{
reserve(1);
buf.ptr[pos++] = c;
}
void putdchar(dchar dc) @trusted
{
import std.utf : encode, UseReplacementDchar;
char[4] ubuf;
immutable size = encode!(UseReplacementDchar.yes)(ubuf, dc);
reserve(size);
foreach (c; ubuf)
buf.ptr[pos++] = c;
}
void putonly(const char[] b) @trusted
{
import core.stdc.string : memcpy;
assert(pos == 0); // assume this is the only put call
if (reserveWithoutAllocating(b.length))
memcpy(buf.ptr + pos, b.ptr, b.length);
else
buf = b.dup;
pos = b.length;
}
}
private struct LockedFile
{
private @system _iobuf* fp;
this(FILE* fps) @trusted
{
_FLOCK(fps);
// Since fps is now locked, we can cast away shared
fp = cast(_iobuf*) fps;
}
@disable this();
@disable this(this);
@disable void opAssign(LockedFile);
// these use unlocked fgetc calls
@trusted fgetc() { return _FGETC(fp); }
@trusted fgetwc() { return _FGETWC(fp); }
~this() @trusted
{
_FUNLOCK(cast(FILE*) fp);
}
}
@safe unittest
{
void f() @safe
{
FILE* fps;
auto lf = LockedFile(fps);
static assert(!__traits(compiles, lf = LockedFile(fps)));
version (ShouldFail)
{
lf.fps = null; // error with -preview=systemVariables
}
}
}
// Private implementation of readln
private size_t readlnImpl(FILE* fps, ref char[] buf, dchar terminator, File.Orientation orientation) @safe
{
version (CRuntime_Microsoft)
{
auto lf = LockedFile(fps);
ReadlnAppender app;
app.initialize(buf);
int c;
while ((c = lf.fgetc()) != -1)
{
app.putchar(cast(char) c);
if (c == terminator)
{
buf = app.data;
return buf.length;
}
}
if (ferror(fps))
StdioException();
buf = app.data;
return buf.length;
}
else static if (__traits(compiles, core.sys.posix.stdio.getdelim))
{
if (orientation == File.Orientation.wide)
{
import core.stdc.wchar_ : fwide;
auto lf = LockedFile(fps);
/* Stream is in wide characters.
* Read them and convert to chars.
*/
version (Windows)
{
buf.length = 0;
for (int c = void; (c = lf.fgetwc()) != -1; )
{
if ((c & ~0x7F) == 0)
{ buf ~= c;
if (c == terminator)
break;
}
else
{
if (c >= 0xD800 && c <= 0xDBFF)
{
int c2 = void;
if ((c2 = lf.fgetwc()) != -1 ||
c2 < 0xDC00 && c2 > 0xDFFF)
{
StdioException("unpaired UTF-16 surrogate");
}
c = ((c - 0xD7C0) << 10) + (c2 - 0xDC00);
}
import std.utf : encode;
encode(buf, c);
}
}
if (ferror(fps))
StdioException();
return buf.length;
}
else version (Posix)
{
buf.length = 0;
for (int c; (c = lf.fgetwc()) != -1; )
{
import std.utf : encode;
if ((c & ~0x7F) == 0)
buf ~= cast(char) c;
else
encode(buf, cast(dchar) c);
if (c == terminator)
break;
}
if (ferror(fps))
StdioException();
return buf.length;
}
else
{
static assert(0);
}
}
return () @trusted {
import core.stdc.stdlib : free;
static char *lineptr = null;
static size_t n = 0;
scope(exit)
{
if (n > 128 * 1024)
{
// Bound memory used by readln
free(lineptr);
lineptr = null;
n = 0;
}
}
const s = core.sys.posix.stdio.getdelim(&lineptr, &n, terminator, fps);
if (s < 0)
{
if (ferror(fps))
StdioException();
buf.length = 0; // end of file
return 0;
}
const line = lineptr[0 .. s];
if (s <= buf.length)
{
buf = buf[0 .. s];
buf[] = line;
}
else
{
buf = line.dup;
}
return s;
}();
}
else // version (NO_GETDELIM)
{
import core.stdc.wchar_ : fwide;
auto lf = LockedFile(fps);
if (orientation == File.Orientation.wide)
{
/* Stream is in wide characters.
* Read them and convert to chars.
*/
version (Windows)
{
buf.length = 0;
for (int c; (c = lf.fgetwc()) != -1; )
{
if ((c & ~0x7F) == 0)
{ buf ~= c;
if (c == terminator)
break;
}
else
{
if (c >= 0xD800 && c <= 0xDBFF)
{
int c2 = void;
if ((c2 = lf.fgetwc()) != -1 ||
c2 < 0xDC00 && c2 > 0xDFFF)
{
StdioException("unpaired UTF-16 surrogate");
}
c = ((c - 0xD7C0) << 10) + (c2 - 0xDC00);
}
import std.utf : encode;
encode(buf, c);
}
}
if (ferror(fps))
StdioException();
return buf.length;
}
else version (Posix)
{
import std.utf : encode;
buf.length = 0;
for (int c; (c = lf.fgetwc()) != -1; )
{
if ((c & ~0x7F) == 0)
buf ~= cast(char) c;
else
encode(buf, cast(dchar) c);
if (c == terminator)
break;
}
if (ferror(fps))
StdioException();
return buf.length;
}
else
{
static assert(0);
}
}
// Narrow stream
// First, fill the existing buffer
for (size_t bufPos = 0; bufPos < buf.length; )
{
immutable c = lf.fgetc();
if (c == -1)
{
buf.length = bufPos;
goto endGame;
}
buf[bufPos++] = cast(char) c;
if (c == terminator)
{
// No need to test for errors in file
buf.length = bufPos;
return bufPos;
}
}
// Then, append to it
for (int c; (c = lf.fgetc()) != -1; )
{
buf ~= cast(char) c;
if (c == terminator)
{
// No need to test for errors in file
return buf.length;
}
}
endGame:
if (ferror(fps))
StdioException();
return buf.length;
}
}
@system unittest
{
static import std.file;
auto deleteme = testFilename();
scope(exit) std.file.remove(deleteme);
std.file.write(deleteme, "abcd\n0123456789abcde\n1234\n");
File f = File(deleteme, "rb");
char[] ln = new char[2];
f.readln(ln);
assert(ln == "abcd\n");
char[] t = ln[0 .. 2];
t ~= 't';
assert(t == "abt");
// https://issues.dlang.org/show_bug.cgi?id=13856: ln stomped to "abtd"
assert(ln == "abcd\n");
// it can also stomp the array length
ln = new char[4];
f.readln(ln);
assert(ln == "0123456789abcde\n");
char[100] buf;
ln = buf[];
f.readln(ln);
assert(ln == "1234\n");
assert(ln.ptr == buf.ptr); // avoid allocation, buffer is good enough
}
/** Experimental network access via the File interface
Opens a TCP connection to the given host and port, then returns
a File struct with read and write access through the same interface
as any other file (meaning writef and the byLine ranges work!).
Authors:
Adam D. Ruppe
Bugs:
Only works on Linux
*/
version (linux)
{
File openNetwork(string host, ushort port)
{
import core.stdc.string : memcpy;
import core.sys.posix.arpa.inet : htons;
import core.sys.posix.netdb : gethostbyname;
import core.sys.posix.netinet.in_ : sockaddr_in;
static import core.sys.posix.unistd;
static import sock = core.sys.posix.sys.socket;
import std.conv : to;
import std.exception : enforce;
import std.internal.cstring : tempCString;
auto h = enforce( gethostbyname(host.tempCString()),
new StdioException("gethostbyname"));
int s = sock.socket(sock.AF_INET, sock.SOCK_STREAM, 0);
enforce(s != -1, new StdioException("socket"));
scope(failure)
{
// want to make sure it doesn't dangle if something throws. Upon
// normal exit, the File struct's reference counting takes care of
// closing, so we don't need to worry about success
core.sys.posix.unistd.close(s);
}
sockaddr_in addr;
addr.sin_family = sock.AF_INET;
addr.sin_port = htons(port);
memcpy(&addr.sin_addr.s_addr, h.h_addr, h.h_length);
enforce(sock.connect(s, cast(sock.sockaddr*) &addr, addr.sizeof) != -1,
new StdioException("Connect failed"));
File f;
f.fdopen(s, "w+", host ~ ":" ~ to!string(port));
return f;
}
}
version (StdUnittest) private string testFilename(string file = __FILE__, size_t line = __LINE__) @safe
{
import std.conv : text;
import std.file : deleteme;
import std.path : baseName;
// filename intentionally contains non-ASCII (Russian) characters for
// https://issues.dlang.org/show_bug.cgi?id=7648
return text(deleteme, "-детка.", baseName(file), ".", line);
}
|