/usr/include/d2/4.6/std/stdio.d is in libphobos2-4.6-dev 0.29.1-4.6.3-1ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 | // Written in the D programming language.
/**
Standard I/O functions that extend $(B std.c.stdio). $(B std.c.stdio)
is $(D_PARAM public)ally imported when importing $(B std.stdio).
Source: $(PHOBOSSRC std/_stdio.d)
Macros:
WIKI=Phobos/StdStdio
Copyright: Copyright Digital Mars 2007-.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(WEB digitalmars.com, Walter Bright),
$(WEB erdani.org, Andrei Alexandrescu)
*/
/* NOTE: This file has been patched from the original DMD distribution to
work with the GDC compiler.
*/
module std.stdio;
public import core.stdc.stdio;
import std.stdiobase;
import core.stdc.errno, core.stdc.stddef, core.stdc.stdlib, core.memory,
core.stdc.string, core.stdc.wchar_;
import std.algorithm, std.array, std.conv, std.exception, std.file, std.format,
std.range, std.string, std.traits, std.typecons,
std.typetuple, std.utf;
version (GNU)
import core.vararg;
version (DigitalMars) version (Windows)
{
// Specific to the way Digital Mars C does stdio
version = DIGITAL_MARS_STDIO;
import std.c.stdio : __fhnd_info, FHND_WCHAR, FHND_TEXT;
}
version (Posix)
{
import core.sys.posix.stdio;
alias core.sys.posix.stdio.fileno fileno;
}
version (linux)
{
// Specific to the way Gnu C does stdio
version = GCC_IO;
extern(C) FILE* fopen64(const char*, const char*);
}
version (OSX)
{
version = GENERIC_IO;
alias core.stdc.stdio.fopen fopen64;
}
version (FreeBSD)
{
version = GENERIC_IO;
alias core.stdc.stdio.fopen fopen64;
}
version (MinGW)
{
version = MINGW_IO;
}
version(Windows)
{
alias core.stdc.stdio.fopen fopen64;
}
version (DIGITAL_MARS_STDIO)
{
extern (C)
{
/* **
* Digital Mars under-the-hood C I/O functions.
* Use _iobuf* for the unshared version of FILE*,
* usable when the FILE is locked.
*/
int _fputc_nlock(int, _iobuf*);
int _fputwc_nlock(int, _iobuf*);
int _fgetc_nlock(_iobuf*);
int _fgetwc_nlock(_iobuf*);
int __fp_lock(FILE*);
void __fp_unlock(FILE*);
int setmode(int, int);
}
alias _fputc_nlock FPUTC;
alias _fputwc_nlock FPUTWC;
alias _fgetc_nlock FGETC;
alias _fgetwc_nlock FGETWC;
alias __fp_lock FLOCK;
alias __fp_unlock FUNLOCK;
alias setmode _setmode;
enum _O_BINARY = 0x8000;
int _fileno(FILE* f) { return f._file; }
alias _fileno fileno;
}
else version (MINGW_IO)
{
extern (C)
{
int setmode(int, int);
}
void flockfile(FILE* fp) { }
void funlockfile(FILE* fp) { }
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); }
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;
enum _O_BINARY = 0x8000;
int _fileno(FILE* f) { return f._file; }
alias _fileno fileno;
}
else version (GCC_IO)
{
/* **
* Gnu under-the-hood C I/O functions; see
* http://gnu.org/software/libc/manual/html_node/I_002fO-on-Streams.html
*/
extern (C)
{
int fputc_unlocked(int, _iobuf*);
int fputwc_unlocked(wchar_t, _iobuf*);
int fgetc_unlocked(_iobuf*);
int fgetwc_unlocked(_iobuf*);
void flockfile(FILE*);
void funlockfile(FILE*);
ssize_t getline(char**, size_t*, FILE*);
ssize_t getdelim (char**, size_t*, int, FILE*);
private size_t fwrite_unlocked(const(void)* ptr,
size_t size, size_t n, _iobuf *stream);
}
version (linux)
{
// declare fopen64 if not already
static if (!is(typeof(fopen64)))
extern (C) FILE* fopen64(in char*, in char*);
}
alias fputc_unlocked FPUTC;
alias fputwc_unlocked FPUTWC;
alias fgetc_unlocked FGETC;
alias fgetwc_unlocked FGETWC;
alias flockfile FLOCK;
alias funlockfile FUNLOCK;
}
else version (GENERIC_IO)
{
extern (C)
{
void flockfile(FILE*);
void funlockfile(FILE*);
}
int fputc_unlocked(int c, _iobuf* fp) { return fputc(c, cast(shared) fp); }
int fputwc_unlocked(wchar_t c, _iobuf* fp)
{
return fputwc(c, cast(shared) fp);
}
int fgetc_unlocked(_iobuf* fp) { return fgetc(cast(shared) fp); }
int fgetwc_unlocked(_iobuf* fp) { return fgetwc(cast(shared) fp); }
alias fputc_unlocked FPUTC;
alias fputwc_unlocked FPUTWC;
alias fgetc_unlocked FGETC;
alias fgetwc_unlocked FGETWC;
alias flockfile FLOCK;
alias funlockfile FUNLOCK;
}
else
{
static assert(0, "unsupported C I/O system");
}
//------------------------------------------------------------------------------
struct ByRecord(Fields...)
{
private:
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()
{
enforce(file.isOpen);
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...)
{
ByRecord!(Fields) byRecord(File f, string format)
{
return typeof(return)(f, format);
}
}
/**
Encapsulates a $(D FILE*). Generally D does not attempt to provide
thin wrappers over equivalent functions in the C standard library, but
manipulating $(D FILE*) values directly is unsafe and error-prone in
many ways. The $(D File) type ensures safe manipulation, automatic
file closing, and a lot of convenience.
The underlying $(D FILE*) handle is maintained in a reference-counted
manner, such that as soon as the last $(D File) variable bound to a
given $(D FILE*) goes out of scope, the underlying $(D FILE*) is
automatically closed.
Example:
----
// test.d
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 $(D FILE*) is closed.
}
----
<pre class=console>
% rdmd test.d Jimmy
% cat test.txt
Hello, Jimmy!
% __
</pre>
*/
struct File
{
private struct Impl
{
FILE * handle = null;
uint refs = uint.max / 2;
string name = null;
bool isPipe;
this(FILE* h, uint r, string n, bool pipe = false)
{
handle = h;
refs = r;
name = n;
isPipe = pipe;
}
}
private Impl * p;
/**
Constructor taking the name of the file to open and the open mode
(with the same semantics as in the C standard library $(WEB
cplusplus.com/reference/clibrary/cstdio/fopen.html, fopen)
function). Throws an exception if the file could not be opened.
Copying one $(D File) object to another results in the two $(D File)
objects referring to the same underlying file.
The destructor automatically closes the file as soon as no $(D File)
object refers to it anymore.
*/
this(string name, in char[] stdioOpenmode = "rb")
{
p = new Impl(errnoEnforce(.fopen(name, stdioOpenmode),
text("Cannot open file `", name, "' in mode `",
stdioOpenmode, "'")),
1, name);
}
~this()
{
if (!p) return;
if (p.refs == 1) close;
else --p.refs;
}
this(this)
{
if (!p) return;
assert(p.refs);
++p.refs;
}
/**
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.
*/
void opAssign(File rhs)
{
swap(p, rhs.p);
}
/**
First calls $(D detach) (throwing on failure), and then attempts to
_open file $(D name) with mode $(D stdioOpenmode). The mode has the
same semantics as in the C standard library $(WEB
cplusplus.com/reference/clibrary/cstdio/fopen.html, fopen) function.
Throws exception in case of error.
*/
void open(string name, in char[] stdioOpenmode = "rb")
{
detach;
auto another = File(name, stdioOpenmode);
swap(this, another);
}
/**
First calls $(D detach) (throwing on failure), and then runs a command
by calling the C standard library function $(WEB
opengroup.org/onlinepubs/007908799/xsh/_popen.html, _popen).
*/
version(Posix) void popen(string command, in char[] stdioOpenmode = "r")
{
detach;
p = new Impl(errnoEnforce(.popen(command, stdioOpenmode),
"Cannot run command `"~command~"'"),
1, command, true);
}
/** Returns $(D true) if the file is opened. */
@property bool isOpen() const
{
return p !is null && p.handle;
}
/**
Returns $(D true) if the file is at end (see $(WEB
cplusplus.com/reference/clibrary/cstdio/feof.html, feof)). The file
must be opened, otherwise an exception is thrown.
*/
@property bool eof() const
{
enforce(p && p.handle, "Calling eof() against an unopened file.");
return .feof(cast(FILE*) p.handle) != 0;
}
/** Returns the name of the file, if any. */
@property string name() const
{
return p.name;
}
/**
If the file is not opened, returns $(D false). Otherwise, returns
$(WEB cplusplus.com/reference/clibrary/cstdio/ferror.html, ferror) for
the file handle.
*/
@property bool error() const
{
return !p.handle || .ferror(cast(FILE*) p.handle);
}
/**
Detaches from the underlying file. If the sole owner, calls $(D close)
and throws if that fails.
*/
void detach()
{
if (!p) return;
// @@@BUG
//if (p.refs == 1) close;
p = null;
}
/**
If the file was unopened, succeeds vacuously. Otherwise closes the
file (by calling $(WEB
cplusplus.com/reference/clibrary/cstdio/fclose.html, fclose)),
throwing on error. Even if an exception is thrown, afterwards the $(D
File) object is empty. This is different from $(D detach) in that it
always closes the file; consequently, all other $(D File) objects
referring to the same handle will see a closed file henceforth.
*/
void close()
{
if (!p) return; // succeed vacuously
if (!p.handle)
{
p = null; // start a new life
return;
}
scope(exit)
{
p.handle = null; // nullify the handle anyway
p.name = null;
--p.refs;
p = null;
}
version (Posix)
{
if (p.isPipe)
{
// Ignore the result of the command
errnoEnforce(.pclose(p.handle) == 0,
"Could not close pipe `"~p.name~"'");
return;
}
}
//fprintf(std.c.stdio.stderr, ("Closing file `"~name~"`.\n\0").ptr);
errnoEnforce(.fclose(p.handle) == 0,
"Could not close file `"~p.name~"'");
}
/**
If the file is not opened, succeeds vacuously. Otherwise, returns
$(WEB cplusplus.com/reference/clibrary/cstdio/_clearerr.html,
_clearerr) for the file handle.
*/
void clearerr()
{
p is null || p.handle is null ||
.clearerr(p.handle);
}
/**
If the file is not opened, throws an exception. Otherwise, calls $(WEB
cplusplus.com/reference/clibrary/cstdio/_fflush.html, _fflush) for the
file handle and throws on error.
*/
void flush()
{
errnoEnforce
(.fflush(enforce(p.handle, "Calling fflush() on an unopened file"))
== 0);
}
/**
If the file is not opened, throws an exception. Otherwise, calls $(WEB
cplusplus.com/reference/clibrary/cstdio/fread.html, fread) for the
file handle and throws on error.
$(D rawRead) always read in binary mode on Windows.
*/
T[] rawRead(T)(T[] buffer)
{
enforce(buffer.length, "rawRead must take a non-empty buffer");
version(Windows)
{
immutable fd = ._fileno(p.handle);
immutable mode = ._setmode(fd, _O_BINARY);
scope(exit) ._setmode(fd, mode);
version(DIGITAL_MARS_STDIO)
{
// @@@BUG@@@ 4243
immutable info = __fhnd_info[fd];
__fhnd_info[fd] &= ~FHND_TEXT;
scope(exit) __fhnd_info[fd] = info;
}
}
immutable result =
.fread(buffer.ptr, T.sizeof, buffer.length, p.handle);
errnoEnforce(!error);
return result ? buffer[0 .. result] : null;
}
unittest
{
std.file.write("deleteme", "\r\n\n\r\n");
scope(exit) std.file.remove("deleteme");
auto f = File("deleteme", "r");
auto buf = f.rawRead(new char[5]);
f.close();
assert(buf == "\r\n\n\r\n");
/+
buf = stdin.rawRead(new char[5]);
assert(buf == "\r\n\n\r\n");
+/
}
/**
If the file is not opened, throws an exception. Otherwise, calls $(WEB
cplusplus.com/reference/clibrary/cstdio/fwrite.html, fwrite) for the
file handle and throws on error.
$(D rawWrite) always write in binary mode on Windows.
*/
void rawWrite(T)(in T[] buffer)
{
version(Windows)
{
flush(); // before changing translation mode
immutable fd = ._fileno(p.handle);
immutable mode = ._setmode(fd, _O_BINARY);
scope(exit) ._setmode(fd, mode);
version(DIGITAL_MARS_STDIO)
{
// @@@BUG@@@ 4243
immutable info = __fhnd_info[fd];
__fhnd_info[fd] &= ~FHND_TEXT;
scope(exit) __fhnd_info[fd] = info;
}
scope(exit) flush(); // before restoring translation mode
}
auto result =
.fwrite(buffer.ptr, T.sizeof, buffer.length, p.handle);
if (result == result.max) result = 0;
errnoEnforce(result == buffer.length,
text("Wrote ", result, " instead of ", buffer.length,
" objects of type ", T.stringof, " to file `",
p.name, "'"));
}
unittest
{
auto f = File("deleteme", "w");
scope(exit) std.file.remove("deleteme");
f.rawWrite("\r\n\n\r\n");
f.close();
assert(std.file.read("deleteme") == "\r\n\n\r\n");
}
/**
If the file is not opened, throws an exception. Otherwise, calls $(WEB
cplusplus.com/reference/clibrary/cstdio/fseek.html, fseek) for the
file handle. Throws on error.
*/
void seek(long offset, int origin = SEEK_SET)
{
enforce(isOpen, "Attempting to seek() in an unopened file");
version (Windows)
{
errnoEnforce(fseek(p.handle, to!int(offset), origin) == 0,
"Could not seek in file `"~p.name~"'");
}
else
{
//static assert(off_t.sizeof == 8);
errnoEnforce(fseeko(p.handle, offset, origin) == 0,
"Could not seek in file `"~p.name~"'");
}
}
unittest
{
auto f = File("deleteme", "w+");
scope(exit) { f.close(); std.file.remove("deleteme"); }
f.rawWrite("abcdefghijklmnopqrstuvwxyz");
f.seek(7);
assert(f.readln() == "hijklmnopqrstuvwxyz");
version (Windows)
{
// No test for large files yet
}
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");
}
}
/**
If the file is not opened, throws an exception. Otherwise, calls $(WEB
cplusplus.com/reference/clibrary/cstdio/ftell.html, ftell) for the
managed file handle. Throws on error.
*/
@property ulong tell() const
{
enforce(isOpen, "Attempting to tell() in an unopened file");
version (Windows)
{
immutable result = ftell(cast(FILE*) p.handle);
}
else
{
immutable result = ftello(cast(FILE*) p.handle);
}
errnoEnforce(result != -1,
"Query ftell() failed for file `"~p.name~"'");
return result;
}
unittest
{
std.file.write("deleteme", "abcdefghijklmnopqrstuvwqxyz");
scope(exit) { std.file.remove("deleteme"); }
auto f = File("deleteme");
auto a = new ubyte[4];
f.rawRead(a);
assert(f.tell == 4, text(f.tell));
}
/**
If the file is not opened, throws an exception. Otherwise, calls $(WEB
cplusplus.com/reference/clibrary/cstdio/_rewind.html, _rewind) for the
file handle. Throws on error.
*/
void rewind()
{
enforce(isOpen, "Attempting to rewind() an unopened file");
.rewind(p.handle);
}
/**
If the file is not opened, throws an exception. Otherwise, calls $(WEB
cplusplus.com/reference/clibrary/cstdio/_setvbuf.html, _setvbuf) for
the file handle.
*/
void setvbuf(size_t size, int mode = _IOFBF)
{
enforce(isOpen, "Attempting to call setvbuf() on an unopened file");
errnoEnforce(.setvbuf(p.handle, null, mode, size) == 0,
"Could not set buffering for file `"~p.name~"'");
}
/**
If the file is not opened, throws an exception. Otherwise, calls
$(WEB cplusplus.com/reference/clibrary/cstdio/_setvbuf.html,
_setvbuf) for the file handle. */
void setvbuf(void[] buf, int mode = _IOFBF)
{
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 `"~p.name~"'");
}
/**
If the file is not opened, throws an exception. Otherwise, writes its
arguments in text format to the file. */
void write(S...)(S args)
{
auto w = lockingTextWriter();
foreach (arg; args)
{
alias typeof(arg) A;
static if (isSomeString!A)
{
put(w, arg);
}
else static if (isIntegral!A)
{
toTextRange(arg, w);
}
else static if (is(Unqual!A == bool))
{
put(w, arg ? "true" : "false");
}
else static if (is(A : char))
{
put(w, arg);
}
else static if (isSomeChar!A)
{
put(w, arg);
}
else
{
// Most general case
std.format.formattedWrite(w, "%s", arg);
}
}
}
/**
If the file is not opened, throws an exception. Otherwise, writes its
arguments in text format to the file, followed by a newline. */
void writeln(S...)(S args)
{
write(args, '\n');
errnoEnforce(.fflush(p.handle) == 0,
"Could not flush file `"~p.name~"'");
}
private enum errorMessage =
"You must pass a formatting string as the first"
" argument to writef or writefln. If no formatting is needed,"
" you may want to use write or writeln.";
/**
If the file is not opened, throws an exception. Otherwise, writes its
arguments in text format to the file, according to the format in the
first argument. */
void writef(S...)(S args) // if (isSomeString!(S[0]))
{
assert(p);
assert(p.handle);
static assert(S.length>0, errorMessage);
static assert(isSomeString!(S[0]), errorMessage);
auto w = lockingTextWriter();
std.format.formattedWrite(w, args);
}
/**
Same as writef, plus adds a newline. */
void writefln(S...)(S args)
{
static assert(S.length>0, errorMessage);
static assert(isSomeString!(S[0]), errorMessage);
auto w = lockingTextWriter;
std.format.formattedWrite(w, args);
w.put('\n');
.fflush(p.handle);
}
/**********************************
Read line from stream $(D fp) and write it to $(D buf[]), including
terminating character.
This is often faster than $(D File.readln(dchar)) because the buffer
is reused each call. Note that reusing the buffer means that the
previous contents of it has to be copied if needed.
Params:
fp = input stream
buf = buffer used to store the resulting line data. buf is
resized as necessary.
Returns:
0 for end of file, otherwise number of characters read
Throws: $(D StdioException) on error
Example:
---
// Reads $(D stdin) and writes it to $(D stdout).
import std.stdio;
int main()
{
char[] buf;
while (stdin.readln(buf))
write(buf);
return 0;
}
---
This method is more efficient than the one in the previous example
because $(D stdin.readln(buf)) reuses (if possible) memory allocated
by $(D buf), whereas $(D buf = stdin.readln()) makes a new memory allocation
with every line. */
S readln(S = string)(dchar terminator = '\n')
{
Unqual!(typeof(S.init[0]))[] buf;
readln(buf, terminator);
return assumeUnique(buf);
}
unittest
{
std.file.write("deleteme", "hello\nworld\n");
scope(exit) std.file.remove("deleteme");
foreach (C; Tuple!(char, wchar, dchar).Types)
{
auto witness = [ "hello\n", "world\n" ];
auto f = File("deleteme");
uint i = 0;
immutable(C)[] buf;
while ((buf = f.readln!(typeof(buf))()).length)
{
assert(i < witness.length);
assert(equal(buf, witness[i++]));
}
assert(i == witness.length);
}
}
/** ditto */
size_t readln(C)(ref C[] buf, dchar terminator = '\n') if (isSomeChar!C)
{
static if (is(C == char))
{
enforce(p && p.handle, "Attempt to read from an unopened file.");
return readlnImpl(p.handle, buf, terminator);
}
else
{
// TODO: optimize this
string s = readln(terminator);
if (!s.length) return 0;
buf.length = 0;
foreach (wchar c; s)
{
buf ~= c;
}
return buf.length;
}
}
/** ditto */
size_t readln(C, R)(ref C[] buf, R terminator)
if (isBidirectionalRange!R && is(typeof(terminator.front == buf[0])))
{
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;
}
unittest
{
std.file.write("deleteme", "hello\n\rworld\nhow\n\rare ya");
auto witness = [ "hello\n\r", "world\nhow\n\r", "are ya" ];
scope(exit) std.file.remove("deleteme");
auto f = File("deleteme");
uint i = 0;
char[] buf;
while (f.readln(buf, "\n\r"))
{
assert(i < witness.length);
assert(buf == witness[i++]);
}
}
uint readf(Data...)(in char[] format, Data data)
{
assert(isOpen);
auto input = LockingTextReader(this);
return formattedRead(input, format, data);
}
unittest
{
std.file.write("deleteme", "hello\nworld\n");
scope(exit) std.file.remove("deleteme");
string s;
auto f = File("deleteme");
f.readf("%s\n", &s);
assert(s == "hello", "["~s~"]");
}
/**
Returns a temporary file by calling $(WEB
cplusplus.com/reference/clibrary/cstdio/_tmpfile.html, _tmpfile). */
static File tmpfile()
{
auto h = errnoEnforce(core.stdc.stdio.tmpfile,
"Could not create temporary file with tmpfile()");
File result = void;
result.p = new Impl(h, 1, null);
return result;
}
/**
Unsafe function that wraps an existing $(D FILE*). The resulting $(D
File) never takes the initiative in closing the file. */
/*private*/ static File wrapFile(FILE* f)
{
File result = void;
//result.p = new Impl(f, uint.max / 2, null);
result.p = new Impl(f, 9999, null);
return result;
}
/**
Returns the $(D FILE*) corresponding to this object.
*/
FILE* getFP()
{
enforce(p && p.handle,
"Attempting to call getFP() on an unopened file");
return p.handle;
}
unittest
{
assert(stdout.getFP == std.c.stdio.stdout);
}
/**
Returns the file number corresponding to this object.
*/
/*version(Posix) */int fileno() const
{
enforce(isOpen, "Attempting to call fileno() on an unopened file");
return .fileno(cast(FILE*) p.handle);
}
/**
Range that reads one line at a time. */
enum KeepTerminator : bool { no, yes }
/// ditto
struct ByLine(Char, Terminator)
{
File file;
Char[] line;
Terminator terminator;
KeepTerminator keepTerminator;
this(File f, KeepTerminator kt = KeepTerminator.no,
Terminator terminator = '\n')
{
file = f;
this.terminator = terminator;
keepTerminator = kt;
}
/// Range primitive implementations.
bool empty() const
{
return !file.isOpen;
}
/// Ditto
Char[] front()
{
if (line is null) popFront();
return line;
}
/// Ditto
void popFront()
{
enforce(file.isOpen);
file.readln(line, terminator);
assert(line !is null, "Bug in File.readln");
if (!line.length)
file.detach;
else if (keepTerminator == KeepTerminator.no
&& std.algorithm.endsWith(line, terminator))
line.length = line.length - 1;
}
}
/**
Convenience function that returns the $(D LinesReader) corresponding
to this file. */
ByLine!(Char, Terminator) byLine(Terminator = char, Char = char)
(KeepTerminator keepTerminator = KeepTerminator.no,
Terminator terminator = '\n')
{
return typeof(return)(this, keepTerminator, terminator);
}
unittest
{
//printf("Entering test at line %d\n", __LINE__);
scope(failure) printf("Failed test at line %d\n", __LINE__);
std.file.write("testingByLine", "asd\ndef\nasdf");
scope(success) std.file.remove("testingByLine");
auto witness = [ "asd", "def", "asdf" ];
uint i;
auto f = File("testingByLine");
scope(exit)
{
f.close;
assert(!f.isOpen);
}
foreach (line; f.byLine())
{
assert(line == witness[i++]);
}
assert(i == witness.length);
i = 0;
f.rewind;
foreach (line; f.byLine(KeepTerminator.yes))
{
assert(line == witness[i++] ~ '\n' || i == witness.length);
}
assert(i == witness.length);
}
template byRecord(Fields...)
{
ByRecord!(Fields) byRecord(string format)
{
return typeof(return)(this, format);
}
}
unittest
{
// scope(failure) printf("Failed test at line %d\n", __LINE__);
// 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++]);
// }
}
/**
* Range that reads a chunk at a time.
*/
struct ByChunk
{
private:
File file_;
ubyte[] chunk_;
public:
this(File file, size_t size)
in
{
assert(size, "size must be larger than 0");
}
body
{
file_ = file;
chunk_ = new ubyte[](size);
popFront();
}
/// Range primitive operations.
@property
bool empty() const
{
return !file_.isOpen;
}
/// Ditto
@property
nothrow ubyte[] front()
{
return chunk_;
}
/// Ditto
void popFront()
{
enforce(!empty, "Cannot call popFront on empty range");
chunk_ = file_.rawRead(chunk_);
if (chunk_.length == 0)
file_.detach();
}
}
/**
Iterates through a file a chunk at a time by using $(D foreach).
Example:
---------
void main()
{
foreach (ubyte[] buffer; stdin.byChunk(4096))
{
... use buffer ...
}
}
---------
The content of $(D buffer) is reused across calls. In the example
above, $(D buffer.length) is 4096 for all iterations, except for the
last one, in which case $(D buffer.length) may be less than 4096 (but
always greater than zero).
In case of an I/O error, an $(D StdioException) is thrown.
*/
ByChunk byChunk(size_t chunkSize)
{
return ByChunk(this, chunkSize);
}
unittest
{
scope(failure) printf("Failed test at line %d\n", __LINE__);
std.file.write("testingByChunk", "asd\ndef\nasdf");
auto witness = ["asd\n", "def\n", "asdf" ];
auto f = File("testingByChunk");
scope(exit)
{
f.close;
assert(!f.isOpen);
std.file.remove("testingByChunk");
}
uint i;
foreach (chunk; f.byChunk(4))
assert(chunk == cast(ubyte[])witness[i++]);
assert(i == witness.length);
}
/**
$(D Range) that locks the file and allows fast writing to it.
*/
struct LockingTextWriter
{
FILE* fps; // the shared file handle
_iobuf* handle; // the unshared version of fps
int orientation;
this(ref File f)
{
enforce(f.p && f.p.handle);
fps = f.p.handle;
orientation = fwide(fps, 0);
FLOCK(fps);
handle = cast(_iobuf*)fps;
}
~this()
{
FUNLOCK(fps);
fps = null;
handle = null;
}
this(this)
{
enforce(fps);
FLOCK(fps);
}
/// Range primitive implementations.
void put(A)(A writeme) if (is(ElementType!A : const(dchar)))
{
static if (isSomeString!A)
alias typeof(writeme[0]) C;
else
alias ElementType!A C;
static assert(!is(C == void));
if (writeme[0].sizeof == 1 && orientation <= 0)
{
//file.write(writeme); causes infinite recursion!!!
//file.rawWrite(writeme);
auto result =
.fwrite(writeme.ptr, C.sizeof, writeme.length, fps);
if (result != writeme.length) errnoEnforce(0);
}
else
{
// put each character in turn
foreach (dchar c; writeme)
{
put(c);
}
}
}
// @@@BUG@@@ 2340
//void front(C)(C c) if (is(C : dchar)) {
/// ditto
void put(C)(C c) if (is(C : const(dchar)))
{
static if (c.sizeof == 1)
{
// simple char
if (orientation <= 0) FPUTC(c, handle);
else FPUTWC(c, handle);
}
else static if (c.sizeof == 2)
{
if (orientation <= 0)
{
if (c <= 0x7F)
{
FPUTC(c, handle);
}
else
{
char[4] buf;
auto b = std.utf.toUTF8(buf, c);
foreach (i ; 0 .. b.length)
FPUTC(b[i], handle);
}
}
else
{
FPUTWC(c, handle);
}
}
else // 32-bit characters
{
if (orientation <= 0)
{
if (c <= 0x7F)
{
FPUTC(c, handle);
}
else
{
char[4] buf = void;
auto b = std.utf.toUTF8(buf, c);
foreach (i ; 0 .. b.length)
FPUTC(b[i], handle);
}
}
else
{
version (Windows)
{
assert(isValidDchar(c));
if (c <= 0xFFFF)
{
FPUTWC(c, handle);
}
else
{
FPUTWC(cast(wchar)
((((c - 0x10000) >> 10) & 0x3FF)
+ 0xD800), handle);
FPUTWC(cast(wchar)
(((c - 0x10000) & 0x3FF) + 0xDC00),
handle);
}
}
else version (Posix)
{
FPUTWC(c, handle);
}
else
{
static assert(0);
}
}
}
}
}
/// Convenience function.
LockingTextWriter lockingTextWriter()
{
return LockingTextWriter(this);
}
/// Get the size of the file, ulong.max if file is not searchable, but still throws if an actual error occurs.
@property ulong size()
{
ulong pos = void;
if (collectException(pos = tell)) return ulong.max;
scope(exit) seek(pos);
seek(0, SEEK_END);
return tell;
}
}
unittest
{
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);
}
struct LockingTextReader
{
private File _f;
private dchar _crt;
this(File f)
{
enforce(f.isOpen);
_f = f;
FLOCK(_f.p.handle);
}
this(this)
{
FLOCK(_f.p.handle);
}
~this()
{
// File locking has its own reference count
if (_f.isOpen) FUNLOCK(_f.p.handle);
}
void opAssign(LockingTextReader r)
{
swap(this, r);
}
@property bool empty()
{
if (!_f.isOpen || _f.eof) return true;
if (_crt == _crt.init)
{
_crt = FGETC(cast(_iobuf*) _f.p.handle);
if (_crt == -1)
{
clear(_f);
return true;
}
else
{
enforce(ungetc(_crt, cast(FILE*) _f.p.handle) == _crt);
}
}
return false;
}
dchar front()
{
enforce(!empty);
return _crt;
}
void popFront()
{
enforce(!empty);
if (FGETC(cast(_iobuf*) _f.p.handle) == -1)
{
enforce(_f.eof);
}
_crt = _crt.init;
}
// void unget(dchar c)
// {
// ungetc(c, cast(FILE*) _f.p.handle);
// }
}
unittest
{
std.file.write("deleteme", "1 2 3");
int x, y;
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);
//pragma(msg, "--- todo: readf ---");
}
private
void writefx(FILE* fps, TypeInfo[] arguments, va_list argptr, int newline=false)
{
int orientation = fwide(fps, 0); // move this inside the lock?
/* Do the file stream locking at the outermost level
* rather than character by character.
*/
FLOCK(fps);
scope(exit) FUNLOCK(fps);
auto fp = cast(_iobuf*)fps; // fp is locked version
if (orientation <= 0) // byte orientation or no orientation
{
void putc(dchar c)
{
if (c <= 0x7F)
{
FPUTC(c, fp);
}
else
{
char[4] buf = void;
foreach (i; 0 .. std.utf.toUTF8(buf, c).length)
FPUTC(buf[i], fp);
}
}
std.format.doFormat(&putc, arguments, argptr);
if (newline)
FPUTC('\n', fp);
}
else if (orientation > 0) // wide orientation
{
version (Windows)
{
void putcw(dchar c)
{
assert(isValidDchar(c));
if (c <= 0xFFFF)
{
FPUTWC(c, fp);
}
else
{
FPUTWC(cast(wchar) ((((c - 0x10000) >> 10) & 0x3FF) +
0xD800), fp);
FPUTWC(cast(wchar) (((c - 0x10000) & 0x3FF) + 0xDC00), fp);
}
}
}
else version (Posix)
{
void putcw(dchar c)
{
FPUTWC(c, fp);
}
}
else
{
static assert(0);
}
std.format.doFormat(&putcw, arguments, argptr);
if (newline)
FPUTWC('\n', fp);
}
}
template isStreamingDevice(T)
{
enum isStreamingDevice = is(T : FILE*) ||
is(T : File);
}
/***********************************
For each argument $(D arg) in $(D args), format the argument (as per
$(LINK2 std_conv.html, to!(string)(arg))) and write the resulting
string to $(D args[0]). A call without any arguments will fail to
compile.
Throws: In case of an I/O error, throws an $(D StdioException).
*/
void write(T...)(T args) if (!is(T[0] : File))
{
stdout.write(args);
}
unittest
{
//printf("Entering test at line %d\n", __LINE__);
scope(failure) printf("Failed test at line %d\n", __LINE__);
void[] buf;
write(buf);
// test write
string file = "dmd-build-test.deleteme.txt";
auto f = File(file, "w");
// scope(exit) { std.file.remove(file); }
f.write("Hello, ", "world number ", 42, "!");
f.close;
assert(cast(char[]) std.file.read(file) == "Hello, world number 42!");
// // test write on stdout
//auto saveStdout = stdout;
//scope(exit) stdout = saveStdout;
//stdout.open(file, "w");
Object obj;
//write("Hello, ", "world number ", 42, "! ", obj);
//stdout.close;
// auto result = cast(char[]) std.file.read(file);
// assert(result == "Hello, world number 42! null", result);
}
/***********************************
* Equivalent to $(D write(args, '\n')). Calling $(D writeln) without
* arguments is valid and just prints a newline to the standard
* output.
*/
void writeln(T...)(T args) if (T.length == 0)
{
enforce(fputc('\n', .stdout.p.handle) == '\n');
}
unittest
{
// Just make sure the call compiles
if (false) writeln();
}
// Specialization for strings - a very frequent case
void writeln(T...)(T args)
if (T.length == 1 && is(typeof(args[0]) : const(char)[]))
{
enforce(fprintf(.stdout.p.handle, "%.*s\n",
cast(int) args[0].length, args[0].ptr) >= 0);
}
unittest
{
if (false) writeln("wyda");
}
// Most general instance
void writeln(T...)(T args)
if (T.length > 1 || T.length == 1 && !is(typeof(args[0]) : const(char)[]))
{
stdout.write(args, '\n');
}
unittest
{
//printf("Entering test at line %d\n", __LINE__);
scope(failure) printf("Failed test at line %d\n", __LINE__);
// test writeln
string file = "dmd-build-test.deleteme.txt";
auto f = File(file, "w");
scope(exit) { std.file.remove(file); }
f.writeln("Hello, ", "world number ", 42, "!");
f.close;
version (Windows)
assert(cast(char[]) std.file.read(file) ==
"Hello, world number 42!\r\n");
else
assert(cast(char[]) std.file.read(file) ==
"Hello, world number 42!\n");
// test writeln on stdout
auto saveStdout = stdout;
scope(exit) stdout = saveStdout;
stdout.open(file, "w");
writeln("Hello, ", "world number ", 42, "!");
stdout.close;
version (Windows)
assert(cast(char[]) std.file.read(file) ==
"Hello, world number 42!\r\n");
else
assert(cast(char[]) std.file.read(file) ==
"Hello, world number 42!\n");
}
/***********************************
* If the first argument $(D args[0]) is a $(D FILE*), use
* $(LINK2 std_format.html#format-string, the format specifier) in
* $(D args[1]) to control the formatting of $(D
* args[2..$]), and write the resulting string to $(D args[0]).
* If $(D arg[0]) is not a $(D FILE*), the call is
* equivalent to $(D writef(stdout, args)).
*
IMPORTANT:
New behavior starting with D 2.006: unlike previous versions,
$(D writef) (and also $(D writefln)) only scans its first
string argument for format specifiers, but not subsequent string
arguments. This decision was made because the old behavior made it
unduly hard to simply print string variables that occasionally
embedded percent signs.
Also new starting with 2.006 is support for positional
parameters with
$(LINK2 http://opengroup.org/onlinepubs/009695399/functions/printf.html,
POSIX) syntax.
Example:
-------------------------
writef("Date: %2$s %1$s", "October", 5); // "Date: 5 October"
------------------------
The positional and non-positional styles can be mixed in the same
format string. (POSIX leaves this behavior undefined.) The internal
counter for non-positional parameters tracks the popFront parameter after
the largest positional parameter already used.
New starting with 2.008: raw format specifiers. Using the "%r"
specifier makes $(D writef) simply write the binary
representation of the argument. Use "%-r" to write numbers in little
endian format, "%+r" to write numbers in big endian format, and "%r"
to write numbers in platform-native format.
*/
void writef(T...)(T args)
{
stdout.writef(args);
}
unittest
{
//printf("Entering test at line %d\n", __LINE__);
scope(failure) printf("Failed test at line %d\n", __LINE__);
// test writef
string file = "dmd-build-test.deleteme.txt";
auto f = File(file, "w");
scope(exit) { std.file.remove(file); }
f.writef("Hello, %s world number %s!", "nice", 42);
f.close;
assert(cast(char[]) std.file.read(file) == "Hello, nice world number 42!");
// test write on stdout
auto saveStdout = stdout;
scope(exit) stdout = saveStdout;
stdout.open(file, "w");
writef("Hello, %s world number %s!", "nice", 42);
stdout.close;
assert(cast(char[]) std.file.read(file) == "Hello, nice world number 42!");
}
/***********************************
* Equivalent to $(D writef(args, '\n')).
*/
void writefln(T...)(T args)
{
stdout.writefln(args);
}
unittest
{
//printf("Entering test at line %d\n", __LINE__);
scope(failure) printf("Failed test at line %d\n", __LINE__);
// test writefln
string file = "dmd-build-test.deleteme.txt";
auto f = File(file, "w");
scope(exit) { std.file.remove(file); }
f.writefln("Hello, %s world number %s!", "nice", 42);
f.close;
version (Windows)
assert(cast(char[]) std.file.read(file) ==
"Hello, nice world number 42!\r\n");
else
assert(cast(char[]) std.file.read(file) ==
"Hello, nice world number 42!\n",
cast(char[]) std.file.read(file));
// test write on stdout
// auto saveStdout = stdout;
// scope(exit) stdout = saveStdout;
// stdout.open(file, "w");
// assert(stdout.isOpen);
// writefln("Hello, %s world number %s!", "nice", 42);
// foreach (F ; TypeTuple!(ifloat, idouble, ireal))
// {
// F a = 5i;
// F b = a % 2;
// writeln(b);
// }
// stdout.close;
// auto read = cast(char[]) std.file.read(file);
// version (Windows)
// assert(read == "Hello, nice world number 42!\r\n1\r\n1\r\n1\r\n", read);
// else
// assert(read == "Hello, nice world number 42!\n1\n1\n1\n", "["~read~"]");
}
/**
* Formatted read one line from stdin.
*/
uint readf(A...)(in char[] format, A args)
{
return stdin.readf(format, args);
}
unittest
{
float f;
if (false) uint x = readf("%s", &f);
char a;
wchar b;
dchar c;
if (false) readf("%s %s %s", &a,&b,&c);
}
/**********************************
* Read line from stream $(D fp).
* Returns:
* $(D null) for end of file,
* $(D char[]) for line read from $(D fp), including terminating character
* Params:
* $(D fp) = input stream
* $(D terminator) = line terminator, '\n' by default
* Throws:
* $(D StdioException) on error
* Example:
* Reads $(D stdin) and writes it to $(D stdout).
---
import std.stdio;
int main()
{
char[] buf;
while ((buf = readln()) != null)
write(buf);
return 0;
}
---
*/
string readln(dchar terminator = '\n')
{
return stdin.readln(terminator);
}
/** ditto */
size_t readln(ref char[] buf, dchar terminator = '\n')
{
return stdin.readln(buf, terminator);
}
/*
* Convenience function that forwards to $(D std.c.stdio.fopen)
* with appropriately-constructed C-style strings.
*/
private FILE* fopen(in char[] name, in char[] mode = "r")
{
const namez = toStringz(name), modez = toStringz(mode);
return fopen64(namez, modez);
}
version (Posix)
{
extern(C) FILE* popen(const char*, const char*);
/***********************************
* Convenience function that forwards to $(D std.c.stdio.popen)
* with appropriately-constructed C-style strings.
*/
FILE* popen(in char[] name, in char[] mode = "r")
{
return popen(toStringz(name), toStringz(mode));
}
}
/*
* Convenience function that forwards to $(D std.c.stdio.fwrite)
* and throws an exception upon error
*/
private void binaryWrite(T)(FILE* f, T obj)
{
immutable result = fwrite(obj.ptr, obj[0].sizeof, obj.length, f);
if (result != obj.length) StdioException();
}
/**
* Iterates through the lines of a file by using $(D 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 $(D line), and the behavior of $(D lines)
changes accordingly:
$(OL $(LI If $(D line) has type $(D string), $(D
wstring), or $(D dstring), a new string of the respective type
is allocated every read.) $(LI If $(D line) has type $(D
char[]), $(D wchar[]), $(D dchar[]), the line's content
will be reused (overwritten) across reads.) $(LI If $(D line)
has type $(D immutable(ubyte)[]), the behavior is similar to
case (1), except that no UTF checking is attempted upon input.) $(LI
If $(D line) has type $(D 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. $(D 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 $(D StdioException) is thrown.
*/
struct lines
{
private File f;
private dchar terminator = '\n';
// private string fileName; // Curretly, no use
this(File f, dchar terminator = '\n')
{
this.f = f;
this.terminator = terminator;
}
// Keep these commented lines for later, when Walter fixes the
// exception model.
// static lines opCall(string fName, dchar terminator = '\n')
// {
// auto f = enforce(fopen(fName),
// new StdioException("Cannot open file `"~fName~"' for reading"));
// auto result = lines(f, terminator);
// result.fileName = fName;
// return result;
// }
int opApply(D)(scope D dg)
{
// scope(exit) {
// if (fileName.length && fclose(f))
// StdioException("Could not close file `"~fileName~"'");
// }
alias ParameterTypeTuple!(dg) Parms;
static if (isSomeString!(Parms[$ - 1]))
{
enum bool duplicate = is(Parms[$ - 1] == string)
|| is(Parms[$ - 1] == wstring) || is(Parms[$ - 1] == dstring);
int result = 0;
static if (is(Parms[$ - 1] : const(char)[]))
alias char C;
else static if (is(Parms[$ - 1] : const(wchar)[]))
alias wchar C;
else static if (is(Parms[$ - 1] : const(dchar)[]))
alias dchar C;
C[] line;
static if (Parms.length == 2)
Parms[0] i = 0;
for (;;)
{
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)
{
alias ParameterTypeTuple!(dg) Parms;
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 buffer arg;
// 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;
}
}
unittest
{
//printf("Entering test at line %d\n", __LINE__);
scope(failure) printf("Failed test at line %d\n", __LINE__);
string file = "dmd-build-test.deleteme.txt";
scope(exit) { std.file.remove(file); }
alias TypeTuple!(string, wstring, dstring,
char[], wchar[], dchar[])
TestedWith;
foreach (T; TestedWith) {
// test looping with an empty file
std.file.write(file, "");
auto f = File(file, "r");
foreach (T line; lines(f))
{
assert(false);
}
f.close;
// test looping with a file with three lines
std.file.write(file, "Line one\nline two\nline three\n");
f.open(file, "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(file, "Line one\nline two\nline three");
f.open(file, "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
//@@@BUG 2612@@@
//alias TypeTuple!(immutable(ubyte)[], ubyte[]) TestedWith2;
alias TypeTuple!(immutable(ubyte)[], ubyte[]) TestedWith2;
foreach (T; TestedWith2) {
// test looping with an empty file
std.file.write(file, "");
auto f = File(file, "r");
foreach (T line; lines(f))
{
assert(false);
}
f.close;
// test looping with a file with three lines
std.file.write(file, "Line one\nline two\nline three\n");
f.open(file, "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(file, "Line one\nline two\nline three");
f.open(file, "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;
}
foreach (T; TypeTuple!(ubyte[]))
{
// test looping with a file with three lines, last without a newline
// using a counter too this time
std.file.write(file, "Line one\nline two\nline three");
auto f = File(file, "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 $(D
foreach).
Example:
---------
void main()
{
foreach (ubyte[] buffer; chunks(stdin, 4096))
{
... use buffer ...
}
}
---------
The content of $(D buffer) is reused across calls. In the
example above, $(D buffer.length) is 4096 for all iterations,
except for the last one, in which case $(D buffer.length) may
be less than 4096 (but always greater than zero).
In case of an I/O error, an $(D StdioException) is thrown.
*/
struct chunks
{
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");
}
body
{
this.f = f;
this.size = size;
}
// static chunks opCall(string fName, size_t size)
// {
// auto f = enforce(fopen(fName),
// new StdioException("Cannot open file `"~fName~"' for reading"));
// auto result = chunks(f, size);
// result.fileName = fName;
// return result;
// }
int opApply(D)(scope D dg)
{
const 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 = core.stdc.stdio.fread(buffer.ptr,
buffer[0].sizeof, size, f.p.handle)) > 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;
}
}
unittest
{
//printf("Entering test at line %d\n", __LINE__);
scope(failure) printf("Failed test at line %d\n", __LINE__);
string file = "dmd-build-test.deleteme.txt";
scope(exit) { std.file.remove(file); }
// test looping with an empty file
std.file.write(file, "");
auto f = File(file, "r");
foreach (ubyte[] line; chunks(f, 4))
{
assert(false);
}
f.close;
// test looping with a file with three lines
std.file.write(file, "Line one\nline two\nline three\n");
f = File(file, "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;
}
/*********************
* Thrown if I/O errors happen.
*/
class StdioException : Exception
{
/// Operating system error code.
uint errno;
/**
Initialize with a message and an error code. */
this(string message, uint e = .getErrno)
{
errno = e;
version (Posix)
{
char[256] buf = void;
version (linux)
{
auto s = std.c.string.strerror_r(errno, buf.ptr, buf.length);
}
else
{
std.c.string.strerror_r(errno, buf.ptr, buf.length);
auto s = buf.ptr;
}
}
else
{
auto s = std.c.string.strerror(errno);
}
auto sysmsg = to!string(s);
super(message ? message ~ "(" ~ sysmsg ~ ")" : sysmsg);
}
/** Convenience functions that throw an $(D StdioException). */
static void opCall(string msg)
{
throw new StdioException(msg);
}
/// ditto
static void opCall()
{
throw new StdioException(null, .getErrno);
}
}
extern(C) void std_stdio_static_this()
{
//Bind stdin, stdout, stderr
__gshared File.Impl stdinImpl;
stdinImpl.handle = core.stdc.stdio.stdin;
.stdin.p = &stdinImpl;
// stdout
__gshared File.Impl stdoutImpl;
stdoutImpl.handle = core.stdc.stdio.stdout;
.stdout.p = &stdoutImpl;
// stderr
__gshared File.Impl stderrImpl;
stderrImpl.handle = core.stdc.stdio.stderr;
.stderr.p = &stderrImpl;
}
//---------
__gshared
{
File stdin;
File stdout;
File stderr;
}
unittest
{
scope(failure) printf("Failed test at line %d\n", __LINE__);
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);
}
}
// Private implementation of readln
version (DIGITAL_MARS_STDIO)
private size_t readlnImpl(FILE* fps, ref char[] buf, dchar terminator = '\n')
{
FLOCK(fps);
scope(exit) FUNLOCK(fps);
/* Since fps is now locked, we can create an "unshared" version
* of fp.
*/
auto fp = cast(_iobuf*)fps;
if (__fhnd_info[fp._file] & FHND_WCHAR)
{ /* Stream is in wide characters.
* Read them and convert to chars.
*/
static assert(wchar_t.sizeof == 2);
auto app = appender(buf);
app.clear();
for (int c = void; (c = FGETWC(fp)) != -1; )
{
if ((c & ~0x7F) == 0)
{ app.put(cast(char) c);
if (c == terminator)
break;
}
else
{
if (c >= 0xD800 && c <= 0xDBFF)
{
int c2 = void;
if ((c2 = FGETWC(fp)) != -1 ||
c2 < 0xDC00 && c2 > 0xDFFF)
{
StdioException("unpaired UTF-16 surrogate");
}
c = ((c - 0xD7C0) << 10) + (c2 - 0xDC00);
}
//std.utf.encode(buf, c);
app.put(cast(dchar)c);
}
}
if (ferror(fps))
StdioException();
buf = app.data;
return buf.length;
}
auto sz = GC.sizeOf(buf.ptr);
//auto sz = buf.length;
buf = buf.ptr[0 .. sz];
if (fp._flag & _IONBF)
{
/* Use this for unbuffered I/O, when running
* across buffer boundaries, or for any but the common
* cases.
*/
L1:
auto app = appender(buf);
app.clear();
if(app.capacity == 0)
app.reserve(128); // get at least 128 bytes available
int c;
while((c = FGETC(fp)) != -1) {
app.put(cast(char) c);
if(c == terminator) {
buf = app.data;
return buf.length;
}
}
if (ferror(fps))
StdioException();
buf = app.data;
return buf.length;
}
else
{
int u = fp._cnt;
char* p = fp._ptr;
int i;
if (fp._flag & _IOTRAN)
{ /* Translated mode ignores \r and treats ^Z as end-of-file
*/
char c;
while (1)
{
if (i == u) // if end of buffer
goto L1; // give up
c = p[i];
i++;
if (c != '\r')
{
if (c == terminator)
break;
if (c != 0x1A)
continue;
goto L1;
}
else
{ if (i != u && p[i] == terminator)
break;
goto L1;
}
}
if (i > sz)
{
buf = uninitializedArray!(char[])(i);
}
if (i - 1)
memcpy(buf.ptr, p, i - 1);
buf[i - 1] = cast(char)terminator;
buf = buf[0 .. i];
if (terminator == '\n' && c == '\r')
i++;
}
else
{
while (1)
{
if (i == u) // if end of buffer
goto L1; // give up
auto c = p[i];
i++;
if (c == terminator)
break;
}
if (i > sz)
{
buf = uninitializedArray!(char[])(i);
}
memcpy(buf.ptr, p, i);
buf = buf[0 .. i];
}
fp._cnt -= i;
fp._ptr += i;
return i;
}
}
version (MINGW_IO)
private size_t readlnImpl(FILE* fps, ref char[] buf, dchar terminator = '\n')
{
FLOCK(fps);
scope(exit) FUNLOCK(fps);
auto fp = cast(_iobuf*)fps;
if (fwide(fps, 0) > 0)
{ /* Stream is in wide characters
* Read them and convert to chars.
*/
version (Windows)
{
buf.length = 0;
for (int c; (c = FGETWC(fp)) != -1; )
{
if ((c & ~0x7F) == 0)
{ buf ~= c;
if (c == terminator)
break;
}
else
{
if (c >= 0xD800 && c <= 0xDBFF)
{
int c2 = void;
if ((c2 = FGETWC(fp)) != -1 ||
c2 < 0xDC00 && c2 > 0xDFFF)
{
StdioException("unpaired UTF-16 surrogate");
}
c = ((c - 0xD7C0) << 10) + (c2 - 0xDC00);
}
std.utf.encode(buf, c);
}
}
if (ferror(cast(shared)fp))
StdioException();
return buf.length;
}
else version (Posix)
{
buf.length = 0;
for (int c; (c = FGETWC(fp)) != -1; )
{
if ((c & ~0x7F) == 0)
buf ~= cast(char)c;
else
std.utf.encode(buf, cast(dchar)c);
if (c == terminator)
break;
}
if (ferror(fps))
StdioException();
return buf.length;
}
else
{
static assert(0);
}
}
// Narrow stream
buf.length = 0;
for (int c; (c = FGETC(fp)) != -1; )
{
buf ~= cast(char)c;
if (c == terminator)
break;
}
if (ferror(fps))
StdioException();
return buf.length;
}
version (GCC_IO)
private size_t readlnImpl(FILE* fps, ref char[] buf, dchar terminator = '\n')
{
if (fwide(fps, 0) > 0)
{ /* Stream is in wide characters.
* Read them and convert to chars.
*/
FLOCK(fps);
scope(exit) FUNLOCK(fps);
auto fp = cast(_iobuf*)fps;
version (Windows)
{
buf.length = 0;
for (int c = void; (c = FGETWC(fp)) != -1; )
{
if ((c & ~0x7F) == 0)
{ buf ~= c;
if (c == terminator)
break;
}
else
{
if (c >= 0xD800 && c <= 0xDBFF)
{
int c2 = void;
if ((c2 = FGETWC(fp)) != -1 ||
c2 < 0xDC00 && c2 > 0xDFFF)
{
StdioException("unpaired UTF-16 surrogate");
}
c = ((c - 0xD7C0) << 10) + (c2 - 0xDC00);
}
std.utf.encode(buf, c);
}
}
if (ferror(fp))
StdioException();
return buf.length;
}
else version (Posix)
{
buf.length = 0;
for (int c; (c = FGETWC(fp)) != -1; )
{
if ((c & ~0x7F) == 0)
buf ~= cast(char)c;
else
std.utf.encode(buf, cast(dchar)c);
if (c == terminator)
break;
}
if (ferror(fps))
StdioException();
return buf.length;
}
else
{
static assert(0);
}
}
char *lineptr = null;
size_t n = 0;
auto s = getdelim(&lineptr, &n, terminator, fps);
scope(exit) free(lineptr);
if (s < 0)
{
if (ferror(fps))
StdioException();
buf.length = 0; // end of file
return 0;
}
buf = buf.ptr[0 .. GC.sizeOf(buf.ptr)];
if (s <= buf.length)
{
buf.length = s;
buf[] = lineptr[0 .. s];
}
else
{
buf = lineptr[0 .. s].dup;
}
return s;
}
version (GENERIC_IO)
private size_t readlnImpl(FILE* fps, ref char[] buf, dchar terminator = '\n')
{
FLOCK(fps);
scope(exit) FUNLOCK(fps);
auto fp = cast(_iobuf*)fps;
if (fwide(fps, 0) > 0)
{ /* Stream is in wide characters.
* Read them and convert to chars.
*/
version (Windows)
{
buf.length = 0;
for (int c; (c = FGETWC(fp)) != -1; )
{
if ((c & ~0x7F) == 0)
{ buf ~= c;
if (c == terminator)
break;
}
else
{
if (c >= 0xD800 && c <= 0xDBFF)
{
int c2 = void;
if ((c2 = FGETWC(fp)) != -1 ||
c2 < 0xDC00 && c2 > 0xDFFF)
{
StdioException("unpaired UTF-16 surrogate");
}
c = ((c - 0xD7C0) << 10) + (c2 - 0xDC00);
}
std.utf.encode(buf, c);
}
}
if (ferror(fp))
StdioException();
return buf.length;
}
else version (Posix)
{
buf.length = 0;
for (int c; (c = FGETWC(fp)) != -1; )
{
if ((c & ~0x7F) == 0)
buf ~= cast(char)c;
else
std.utf.encode(buf, cast(dchar)c);
if (c == terminator)
break;
}
if (ferror(fps))
StdioException();
return buf.length;
}
else
{
static assert(0);
}
}
// Narrow stream
buf.length = 0;
for (int c; (c = FGETC(fp)) != -1; )
{
buf ~= cast(char)c;
if (c == terminator)
break;
}
if (ferror(fps))
StdioException();
return buf.length;
}
/** 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) {
static import linux = std.c.linux.linux;
static import sock = std.c.linux.socket;
File openNetwork(string host, ushort port) {
auto h = enforce( sock.gethostbyname(std.string.toStringz(host)),
new StdioException("gethostbyname"));
int s = sock.socket(sock.AF_INET, sock.SOCK_STREAM, 0);
enforce(s != -1, new StdioException("socket"));
scope(failure) {
linux.close(s); // 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
}
sock.sockaddr_in addr;
addr.sin_family = sock.AF_INET;
addr.sin_port = sock.htons(port);
std.c.string.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* fp = enforce(fdopen(s, "w+".ptr));
File f;
f.p = new File.Impl(fp, 1, host ~ ":" ~ to!string(port));
return f;
}
}
|