├── .gitignore ├── LICENSE ├── README.md ├── chapter-1-introduction ├── 1.hello.c ├── 10.file-copying-2nd.c ├── 11.file-copying-3rd.c ├── 12.print-eof.c ├── 13.character-counting.c ├── 14.character-counting-for-double.c ├── 15.line-counting.c ├── 16.space-tab-line-counting.c ├── 17.repalce-multi-space.c ├── 18.replace-tab-backspace-backslash.c ├── 19.word-counting.c ├── 2.hello.c ├── 20.print-words.c ├── 21.array.c ├── 22.words-length-histogram-horizontal.c ├── 23.words-length-histogram-vertical.c ├── 24.characters-frequencies-histogram.c ├── 25.function-power.c ├── 26.fahrenheit-celsius-table-function.c ├── 27.max-line.c ├── 28.print-input-line-and-text.c ├── 29.print-length-80-line.c ├── 3.fahrenheit-celsius-table.c ├── 30.remove-line-end-space-and-tab.c ├── 31.reverses.c ├── 32.external-variables-and-scope.c ├── 33.detab.c ├── 34.entab.c ├── 35.fold-line.c ├── 36.remove-comments.c ├── 4.fahrenheit-celsius-table-float.c ├── 5.celsius-fahrenheit-table.c ├── 6.fahrenheit-celsius-table-for.c ├── 7.fahrenheit-celsius-table-reverse.c ├── 8.symbolic-constants.c └── 9.file-copying-1st.c ├── chapter-2-types-operators-expressions ├── 1.ranges-of-variables.c ├── 10.getbits.c ├── 11.setbits.c ├── 12.invert.c ├── 13.rightrot.c ├── 14.bitcount.c ├── 15.bitcount2.c ├── 16.lower2.c ├── 2.loop-without-logical-operators.c ├── 3.atoi.c ├── 4.lower.c ├── 5.htio.c ├── 6.squeeze.c ├── 7.strcat.c ├── 8.squeeze2.c └── 9.any.c ├── chapter-3-control-flow ├── 01.binsearch.c ├── 02.switch.c ├── 03.escape.c ├── 04.unescape.c ├── 05.atoi.c ├── 06.shellsort.c ├── 07.reverse.c ├── 08.expand.c ├── 09.itoa.c ├── 10.itob.c ├── 11.itoa.c └── 12.trim.c ├── chapter-4-functions-and-program-structure ├── 1.simple-grep.c ├── 10.reverse.recursive.c ├── 11.swap-macro.c ├── 12.conditional-inclusion.c ├── 2.strrindex.c ├── 3.atof-test.c ├── 4.reverse-polish-calculator.c ├── 5.getop-with-static.c ├── 6.register-variable.c ├── 7.printd.c ├── 8.qsort.c ├── 9.itoa-recursive.c ├── atof.c ├── calc.h ├── getch.c ├── getop.c ├── mygetline.c ├── stack.c └── sysv.h ├── chapter-5-pointers-and-arrays ├── 1.pointer.c ├── 10.strcpy-pointer-v1.c ├── 11.strcpy-pointer-v2.c ├── 12.strcpy-pointer-v3.c ├── 13.strcmp-array-subscript.c ├── 14.strcmp-pointer.c ├── 15.strcat-pointer.c ├── 16.strend.c ├── 17.strncpy.c ├── 18.strncat.c ├── 19.strncmp.c ├── 2.swap.c ├── 20.getline-pointer.c ├── 21.atoi.c ├── 22.itoa.c ├── 23.pointer-arrays.c ├── 24.pointer-arrays-without-alloc.c ├── 25.year-month-day.c ├── 26.pointer-array-init.c ├── 27.year-month-day-pointer.c ├── 28.echo-v1.c ├── 29.echo-v2.c ├── 3.getint.c ├── 30.find.c ├── 31.find.c ├── 32.expr.c ├── 33.detab.c ├── 34.entab.c ├── 35.detab-arg.c ├── 36.entab-arg.c ├── 37.tail.c ├── 38.pointers-to-functions.c ├── 39.sort-with-r.c ├── 4.getfloat.c ├── 40.sort-with-f.c ├── 41.sort-with-d.c ├── 42.dcl.c ├── 43.dcl-error-handle.c ├── 44.undcl.c ├── 44.undcl.test ├── 5.strlen-pointer.c ├── 6.alloc.c ├── 7.alloc.test.c ├── 8.strlen-address-arithmetic.c ├── 9.strcpy-array-subscript.c ├── bigtext ├── case-convert.c ├── getch.c ├── mygetline.c ├── numcmp.c └── readlines-writelines.c ├── chapter-6-structures ├── 1.structures-and-functions.c ├── 2.keywords-count.c ├── 3.getword.c ├── 4.keywords-count-pointer.c ├── 5.words-count-binary-tree.c ├── 6.variables-group.c ├── 7.words-appear-lines.c ├── 8.table-lookup.c └── getch.c ├── chapter-7-input-and-output ├── cat-v1.c ├── cat-v2.c ├── minprintf.c └── scanf-sample.c └── chapter-8-the-unix-system-interface ├── cp.c ├── dirent.h ├── fopen.c ├── fsize.c ├── malloc.c └── sys-copy.c /.gitignore: -------------------------------------------------------------------------------- 1 | *.out 2 | *.txt 3 | *.swp 4 | test.c 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The-C-Programming-Language-2nd-Edition 2 | Source code and solutions of exercises to _The C Programming Language 2nd Edition by Brian W. Kernighan and Dennis M. Ritchie_ 3 | 4 | ## Exercises: 5 | 6 | ### 1. Introduction 7 | 1. [1-1](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/1.hello.c) 8 | 1. [1-2](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/2.hello.c) 9 | 1. [1-3](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/5.celsius-fahrenheit-table.c) 10 | 1. [1-4](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/5.celsius-fahrenheit-table.c) 11 | 1. [1-5](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/7.fahrenheit-celsius-table-reverse.c) 12 | 1. [1-6](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/11.file-copying-3rd.c) 13 | 1. [1-7](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/12.print-eof.c) 14 | 1. [1-8](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/16.space-tab-line-counting.c) 15 | 1. [1-9](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/17.repalce-multi-space.c) 16 | 1. [1-10](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/18.replace-tab-backspace-backslash.c) 17 | 1. 1-11 skipped 18 | 1. [1-12](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/20.print-words.c) 19 | 1. 1-13 20 | * [horizontal](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/22.words-length-histogram-horizontal.c) 21 | * [vertical](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/23.words-length-histogram-vertical.c) 22 | 1. [1-14](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/24.characters-frequencies-histogram.c) 23 | 1. [1-15](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/26.fahrenheit-celsius-table-function.c) 24 | 1. [1-16](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/28.print-input-line-and-text.c) 25 | 1. [1-17](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/29.print-length-80-line.c) 26 | 1. [1-18](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/30.remove-line-end-space-and-tab.c) 27 | 1. [1-19](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/31.reverses.c) 28 | 1. [1-20](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/33.detab.c) 29 | 1. [1-21](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/34.entab.c) 30 | 1. [1-22](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/35.fold-line.c) 31 | 1. [1-23](https://github.com/Heatwave/The-C-Programming-Language-2nd-Edition/blob/master/chapter-1-introduction/36.remove-comments.c) 32 | 1. 1-24 skipped 33 | 34 | ### 2. Types operators expressions 35 | 1. [2-1](./chapter-2-types-operators-expressions/1.ranges-of-variables.c) 36 | 1. [2-2](./chapter-2-types-operators-expressions/2.loop-without-logical-operators.c) 37 | 1. [2-3](./chapter-2-types-operators-expressions/3.atoi.c) 38 | 1. [2-4](./chapter-2-types-operators-expressions/8.squeeze2.c) 39 | 1. [2-5](./chapter-2-types-operators-expressions/9.any.c) 40 | 1. [2-6](./chapter-2-types-operators-expressions/11.setbits.c) 41 | 1. [2-7](./chapter-2-types-operators-expressions/12.invert.c) 42 | 1. [2-8](./chapter-2-types-operators-expressions/13.rightrot.c) 43 | 1. [2-9](./chapter-2-types-operators-expressions/15.bitcount2.c) 44 | 1. [2-10](./chapter-2-types-operators-expressions/16.lower2.c) 45 | 46 | ### 3. Control flow 47 | 1. [3-1](./chapter-3-control-flow/01.binsearch.c) 48 | 1. 3-2 49 | * [escape](./chapter-3-control-flow/03.escape.c) 50 | * [unescape](./chapter-3-control-flow/04.unescape.c) 51 | 1. [3-3](./chapter-3-control-flow/08.expand.c) 52 | 1. [3-4](./chapter-3-control-flow/09.itoa.c) 53 | 1. [3-5](./chapter-3-control-flow/10.itob.c) 54 | 1. [3-6](./chapter-3-control-flow/11.itoa.c) 55 | 56 | ### 4. Functions and program structure 57 | 1. [4-1](./chapter-4-functions-and-program-structure/2.strrindex.c) 58 | 1. [4-2](./chapter-4-functions-and-program-structure/3.atof-test.c) 59 | 1. [4-3, 4-3, 4-5, 4-6](./chapter-4-functions-and-program-structure/4.reverse-polish-calculator.c) 60 | 1. [4-7](./chapter-4-functions-and-program-structure/getch.c) 61 | 1. [4-8](./chapter-4-functions-and-program-structure/getch.c) 62 | 1. 4-9 skipped 63 | 1. 4-10 skipped 64 | 1. [4-11](./chapter-4-functions-and-program-structure/5.getop-with-static.c) 65 | 1. [4-12](./chapter-4-functions-and-program-structure/9.itoa-recursive.c) 66 | 1. [4-13](./chapter-4-functions-and-program-structure/10.reverse.recursive.c) 67 | 1. [4-14](./chapter-4-functions-and-program-structure/11.swap-macro.c) 68 | 69 | ### 5. pointers and arrays 70 | 1. [5-1](./chapter-5-pointers-and-arrays/3.getint.c) 71 | 1. [5-2](./chapter-5-pointers-and-arrays/4.getfloat.c) 72 | 1. [5-3](./chapter-5-pointers-and-arrays/15.strcat-pointer.c) 73 | 1. [5-4](./chapter-5-pointers-and-arrays/16.strend.c) 74 | 1. 5-5 75 | * [strcpy](17.strncpy.c) 76 | * [strncat](18.strncat.c) 77 | * [strncmp](19.strncmp.c) 78 | 1. [5-6](./chapter-5-pointers-and-arrays/20.getline-pointer.c) 79 | 1. [5-7](./chapter-5-pointers-and-arrays/24.pointer-arrays-without-alloc.c) 80 | 1. [5-8](./chapter-5-pointers-and-arrays/27.year-month-day-pointer.c) 81 | 1. [5-9](./chapter-5-pointers-and-arrays/27.year-month-day-pointer.c) 82 | 1. [5-10](./chapter-5-pointers-and-arrays/32.expr.c) 83 | 1. 5-11 84 | * [detab](./chapter-5-pointers-and-arrays/33.detab.c) 85 | * [entab](./chapter-5-pointers-and-arrays/34.entab.c) 86 | 1. 5-12 87 | * [detab](./chapter-5-pointers-and-arrays/35.detab-arg.c) 88 | * [entab](./chapter-5-pointers-and-arrays/36.entab-arg.c) 89 | 1. [5-13](./chapter-5-pointers-and-arrays/37.tail.c) 90 | 1. [5-14](./chapter-5-pointers-and-arrays/39.sort-with-r.c) 91 | 1. [5-15](./chapter-5-pointers-and-arrays/40.sort-with-f.c) 92 | 1. [5-16](./chapter-5-pointers-and-arrays/41.sort-with-d.c) 93 | 1. 5-17 skipped 94 | 1. [5-18](./chapter-5-pointers-and-arrays/43.dcl-error-handle.c) 95 | 1. [5-19](./chapter-5-pointers-and-arrays/44.undcl.c) 96 | 1. 5-20 skipped 97 | 98 | ### 6. structures 99 | 1. [6-1](./chapter-6-structures/3.getword.c) 100 | 1. [6-2](./chapter-6-structures/6.variables-group.c) 101 | 1. [6-3](./chapter-6-structures/7.words-appear-lines.c) 102 | 1. 6-4 skipped 103 | 1. [6-5](./chapter-6-structures/8.table-lookup.c) 104 | 1. 6-6 skipped 105 | -------------------------------------------------------------------------------- /chapter-1-introduction/1.hello.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | printf("hello, world \n"); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /chapter-1-introduction/10.file-copying-2nd.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* copy input to output; 2nd version */ 4 | main() 5 | { 6 | int c; 7 | 8 | while ((c = getchar()) != EOF) 9 | putchar(c); 10 | } 11 | -------------------------------------------------------------------------------- /chapter-1-introduction/11.file-copying-3rd.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | int c; 6 | 7 | c = getchar() != EOF; 8 | 9 | printf("%d\n", c); 10 | putchar(c); 11 | } 12 | -------------------------------------------------------------------------------- /chapter-1-introduction/12.print-eof.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | printf("%d\n", EOF); 6 | } 7 | -------------------------------------------------------------------------------- /chapter-1-introduction/13.character-counting.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* count characters in input; 1st version */ 4 | main() 5 | { 6 | long int nc; 7 | 8 | nc = 0; 9 | while (getchar() != EOF) 10 | ++nc; 11 | printf("%ld\n", nc); 12 | } 13 | -------------------------------------------------------------------------------- /chapter-1-introduction/14.character-counting-for-double.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* count characters in input; 2nd version */ 4 | main() 5 | { 6 | double nc; 7 | 8 | for (nc = 0; getchar() != EOF; ++nc) 9 | ; 10 | printf("%.0f\n", nc); 11 | } 12 | -------------------------------------------------------------------------------- /chapter-1-introduction/15.line-counting.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | int c, nl; 6 | 7 | nl = 0; 8 | while ((c = getchar()) != EOF) 9 | if (c == '\n') 10 | ++nl; 11 | printf("%d\n", nl); 12 | } 13 | -------------------------------------------------------------------------------- /chapter-1-introduction/16.space-tab-line-counting.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | int c; 6 | int space, tab, nl; 7 | 8 | space = tab = nl = 0; 9 | 10 | while((c = getchar()) != EOF) { 11 | if (c == ' ') { 12 | space++; 13 | } else if (c == '\t') { 14 | tab++; 15 | } else if (c == '\n') { 16 | nl++; 17 | } 18 | } 19 | printf("space: %d\ntab: %d\nnew line: %d\n", space, tab, nl); 20 | } 21 | -------------------------------------------------------------------------------- /chapter-1-introduction/17.repalce-multi-space.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | int c, pre; 6 | 7 | while ((c = getchar()) != EOF) { 8 | if (c != ' ' || pre != ' ') { 9 | putchar(c); 10 | } 11 | pre = c; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /chapter-1-introduction/18.replace-tab-backspace-backslash.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | int c; 6 | 7 | while ((c = getchar()) != EOF) { 8 | if (c == '\t') { 9 | putchar('\\'); 10 | c = 't'; 11 | } 12 | 13 | if (c == '\b') { 14 | putchar('\\'); 15 | c = 'b'; 16 | } 17 | 18 | if (c == '\\') { 19 | putchar('\\'); 20 | c = '\\'; 21 | } 22 | 23 | putchar(c); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /chapter-1-introduction/19.word-counting.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define IN 1 4 | #define OUT 0 5 | 6 | main() 7 | { 8 | int c, nl, nw, nc, state; 9 | 10 | state = OUT; 11 | nl = nw = nc = 0; 12 | while ((c = getchar()) != EOF) { 13 | ++nc; 14 | if (c == '\n') 15 | ++nl; 16 | if (c == ' ' || c == '\n' || c == '\t') 17 | state = OUT; 18 | else if (state == OUT) { 19 | state = IN; 20 | ++nw; 21 | } 22 | } 23 | 24 | printf("%d %d %d\n", nl, nw, nc); 25 | } 26 | -------------------------------------------------------------------------------- /chapter-1-introduction/2.hello.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | printf("Hello, World\c"); 5 | } 6 | -------------------------------------------------------------------------------- /chapter-1-introduction/20.print-words.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define IN 1 4 | #define OUT 0 5 | 6 | main() 7 | { 8 | int c, state; 9 | 10 | state = OUT; 11 | 12 | while ((c = getchar()) != EOF) { 13 | if (c == ' ' || c == '\n' || c == '\t') { 14 | if (state == IN) { 15 | putchar('\n'); 16 | } 17 | state = OUT; 18 | } else { 19 | state = IN; 20 | putchar(c); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /chapter-1-introduction/21.array.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | int c, i, nwhite, nother; 6 | int ndigit[10]; 7 | 8 | nwhite = nother = 0; 9 | for (i = 0; i < 10; ++i) 10 | ndigit[i] = 0; 11 | 12 | 13 | while ((c = getchar()) != EOF) 14 | if (c >= '0' && c <= '9') 15 | ++ndigit[c-'0']; 16 | else if (c== ' ' || c == '\n' || c == '\t') 17 | ++nwhite; 18 | else 19 | ++nother; 20 | 21 | printf("digits = "); 22 | for (i = 0; i < 10; ++i) 23 | printf(" %d", ndigit[i]); 24 | printf(", white space = %d, other = %d\n", 25 | nwhite, nother); 26 | } 27 | -------------------------------------------------------------------------------- /chapter-1-introduction/22.words-length-histogram-horizontal.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define IN 0 4 | #define OUT 1 5 | 6 | main() 7 | { 8 | int state; 9 | int length, max; 10 | int count[999]; 11 | int i, c, j; 12 | 13 | length = 0; 14 | max = 0; 15 | state = OUT; 16 | 17 | for (i = 0; i < 999; ++i) 18 | count[i] = 0; 19 | 20 | while ((c = getchar()) != EOF) { 21 | if (c == ' ' || c == '\n' || c == '\t') { 22 | state = OUT; 23 | 24 | if (length > max) 25 | max = length; 26 | 27 | if (length != 0) 28 | count[length]++; 29 | length = 0; 30 | } else if (state == OUT) { 31 | state = IN; 32 | length++; 33 | } else { 34 | length++; 35 | } 36 | } 37 | 38 | for (i = 0; i < max + 1; ++i) { 39 | printf("%2d: ", i); 40 | for (j = 0; j < count[i]; ++j) { 41 | putchar('#'); 42 | } 43 | printf("\n"); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /chapter-1-introduction/23.words-length-histogram-vertical.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define IN 0 4 | #define OUT 1 5 | #define WORD_MAX_LENGTH 999 6 | 7 | main() 8 | { 9 | int state; 10 | int length, maxLength, maxCount; 11 | int count[WORD_MAX_LENGTH]; 12 | int i, c, j; 13 | 14 | length = 0; 15 | maxLength = 0; 16 | maxCount = 0; 17 | state = OUT; 18 | 19 | for (i = 0; i < WORD_MAX_LENGTH; ++i) 20 | count[i] = 0; 21 | 22 | while ((c = getchar()) != EOF) { 23 | if (c == ' ' || c == '\n' || c == '\t') { 24 | state = OUT; 25 | 26 | if (length > maxLength) 27 | maxLength = length; 28 | 29 | if (length != 0) 30 | count[length]++; 31 | 32 | if (count[length] > maxCount) 33 | maxCount = count[length]; 34 | 35 | length = 0; 36 | } else if (state == OUT) { 37 | state = IN; 38 | length++; 39 | } else { 40 | length++; 41 | } 42 | } 43 | 44 | for (i = maxCount; i > 0; --i) { 45 | printf("%2d: ", i); 46 | 47 | for (j = 1; j < maxLength + 1; ++j) { 48 | printf(" "); 49 | if (count[j] >= i) 50 | putchar('#'); 51 | else 52 | putchar(' '); 53 | } 54 | putchar('\n'); 55 | } 56 | 57 | printf(" "); 58 | for (i = 1; i < maxLength + 1; ++i) 59 | printf("%3d", i); 60 | 61 | printf("\n"); 62 | } 63 | -------------------------------------------------------------------------------- /chapter-1-introduction/24.characters-frequencies-histogram.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | int histogram[26]; 6 | int c, i, j; 7 | 8 | for (i = 0; i < 26; ++i) 9 | histogram[i] = 0; 10 | 11 | while ((c = getchar()) != EOF) { 12 | if (c >= 'a' && c <= 'z') { 13 | histogram[c - 'a']++; 14 | } 15 | } 16 | 17 | for (i = 0; i < 26; ++i) { 18 | printf("%c: ", 'a' + i); 19 | for (j = 0; j < histogram[i]; ++j) { 20 | putchar('#'); 21 | } 22 | putchar('\n'); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /chapter-1-introduction/25.function-power.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int power(int m, int n); 4 | 5 | main() 6 | { 7 | int i; 8 | 9 | for (i = 0; i < 10; ++i) 10 | printf("%d %d %d\n", i, power(2, i), power(-3, i)); 11 | return 0; 12 | } 13 | 14 | int power(int base, int n) 15 | { 16 | int i, p; 17 | 18 | p = 1; 19 | for (i = 1; i <= n; ++i) 20 | p = p * base; 21 | return p; 22 | } 23 | -------------------------------------------------------------------------------- /chapter-1-introduction/26.fahrenheit-celsius-table-function.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | float fahrToCelsius(float fahr); 4 | 5 | main() 6 | { 7 | float fahr, celsius; 8 | int lower, upper, step; 9 | 10 | lower = 0; /* lower limit of temperature table */ 11 | upper = 300; /* upper limit */ 12 | step = 20; /* step size */ 13 | 14 | fahr = lower; 15 | 16 | printf("Fahrenheit-Celsius table\n"); 17 | while (fahr <= upper) { 18 | printf("%3.0f %6.1f\n", fahr, fahrToCelsius(fahr)); 19 | fahr = fahr + step; 20 | } 21 | } 22 | 23 | float fahrToCelsius(float fahr) 24 | { 25 | return (5.0 / 9.0) * (fahr - 32.0); 26 | } 27 | -------------------------------------------------------------------------------- /chapter-1-introduction/27.max-line.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAXLINE 1000 4 | 5 | int myGetline(char line[], int maxline); 6 | void copy(char to[], char from[]); 7 | 8 | main() 9 | { 10 | int len; 11 | int max; 12 | char line[MAXLINE]; 13 | char longest[MAXLINE]; 14 | 15 | max = 0; 16 | while ((len = myGetline(line, MAXLINE)) > 0) 17 | if (len > max) { 18 | max = len; 19 | copy(longest, line); 20 | } 21 | 22 | if (max > 0) 23 | printf("%s", longest); 24 | 25 | return 0; 26 | } 27 | 28 | int myGetline(char s[], int lim) 29 | { 30 | int c, i; 31 | 32 | for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) 33 | s[i] = c; 34 | if (c == '\n') { 35 | s[i] = c; 36 | ++i; 37 | } 38 | s[i] = '\0'; 39 | return i; 40 | } 41 | 42 | void copy(char to[], char from[]) 43 | { 44 | int i; 45 | 46 | i = 0; 47 | while ((to[i] = from[i]) != '\0') 48 | ++i; 49 | } 50 | -------------------------------------------------------------------------------- /chapter-1-introduction/28.print-input-line-and-text.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAXLINE 1000 4 | 5 | int myGetline(char line[], int maxline); 6 | char 7 | 8 | main() 9 | { 10 | int len; 11 | int max; 12 | char line[MAXLINE]; 13 | 14 | max = 0; 15 | while ((len = myGetline(line, MAXLINE)) > 0) 16 | printf("%d: %s", len, line); 17 | 18 | return 0; 19 | } 20 | 21 | int myGetline(char s[], int lim) 22 | { 23 | int c, i; 24 | 25 | i = 0; 26 | 27 | while((c = getchar()) != EOF && c != '\n') { 28 | if (i < lim - 1) 29 | s[i++] = c; 30 | else 31 | i++; 32 | } 33 | 34 | if (c == '\n' && i < lim - 1) { 35 | s[i++] = c; 36 | } 37 | s[i] = '\0'; 38 | return i; 39 | } 40 | -------------------------------------------------------------------------------- /chapter-1-introduction/29.print-length-80-line.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAXLINE 1000 4 | #define PRINT_LENGTH 80 5 | 6 | int myGetline(char line[], int maxline); 7 | char 8 | 9 | main() 10 | { 11 | int len; 12 | int max; 13 | char line[MAXLINE]; 14 | char longest[MAXLINE]; 15 | 16 | max = 0; 17 | while ((len = myGetline(line, MAXLINE)) > 0) 18 | if (len > PRINT_LENGTH) { 19 | printf("%s", line); 20 | } 21 | 22 | return 0; 23 | } 24 | 25 | int myGetline(char s[], int lim) 26 | { 27 | int c, i; 28 | 29 | for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) 30 | s[i] = c; 31 | if (c == '\n') { 32 | s[i] = c; 33 | ++i; 34 | } 35 | s[i] = '\0'; 36 | return i; 37 | } 38 | -------------------------------------------------------------------------------- /chapter-1-introduction/3.fahrenheit-celsius-table.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* print Fahrenheit-Celsius table 4 | for fahr = 0, 20, ..., 300 */ 5 | main() { 6 | int fahr, celsius; 7 | int lower, upper, step; 8 | 9 | lower = 0; /* lower limit of temperature table */ 10 | upper = 300; /* upper limit */ 11 | step = 20; /* step size */ 12 | 13 | fahr = lower; 14 | while (fahr <= upper) { 15 | celsius = 5 * (fahr-32) / 9; 16 | printf("%3d %6d\n", fahr, celsius); 17 | fahr = fahr + step; 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /chapter-1-introduction/30.remove-line-end-space-and-tab.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAXLINE 1000 4 | 5 | int myGetline(char line[], int maxline); 6 | char 7 | 8 | main() 9 | { 10 | int len; 11 | int max; 12 | char line[MAXLINE]; 13 | char longest[MAXLINE]; 14 | int i; 15 | 16 | max = 0; 17 | while ((len = myGetline(line, MAXLINE)) > 0) { 18 | for (i = len; i >= 0; --i) { 19 | if (line[i] == ' ' || line[i] == '\t') 20 | line[i] = '\0'; 21 | else if (line[i] == '\n' || line[i] == '\0') 22 | continue; 23 | else 24 | break; 25 | } 26 | 27 | if (line[0] != '\0' && line[0] != '\n') { 28 | printf("%s", line); 29 | } 30 | } 31 | 32 | return 0; 33 | } 34 | 35 | int myGetline(char s[], int lim) 36 | { 37 | int c, i; 38 | 39 | for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) 40 | s[i] = c; 41 | if (c == '\n') { 42 | s[i] = c; 43 | ++i; 44 | } 45 | s[i] = '\0'; 46 | return i; 47 | } 48 | -------------------------------------------------------------------------------- /chapter-1-introduction/31.reverses.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAXLINE 999 4 | 5 | void reverse(char s[]); 6 | int myGetline(char line[], int maxline); 7 | 8 | int main() 9 | { 10 | char line[MAXLINE]; 11 | 12 | while(myGetline(line, MAXLINE) > 0) { 13 | reverse(line); 14 | printf("%s", line); 15 | } 16 | 17 | return 0; 18 | } 19 | 20 | void reverse(char s[]) 21 | { 22 | int len, i, left; 23 | char temp; 24 | len = 0; 25 | while (s[len] != '\n') 26 | len++; 27 | 28 | int middle; 29 | if ((len % 2) == 0) 30 | middle = len / 2; 31 | else 32 | middle = len / 2 + 1; 33 | 34 | for (i = len - 1; i >= middle; --i) { 35 | left = len - 1 - i; 36 | temp = s[left]; 37 | s[left] = s[i]; 38 | s[i] = temp; 39 | } 40 | } 41 | 42 | int myGetline(char s[], int maxline) 43 | { 44 | int c, i; 45 | 46 | for (i = 0; i < maxline -1 && (c = getchar()) != EOF && c!= '\n'; ++i) 47 | s[i] = c; 48 | if (c == '\n') { 49 | s[i] = c; 50 | ++i; 51 | } 52 | s[i] = '\0'; 53 | return i; 54 | } 55 | -------------------------------------------------------------------------------- /chapter-1-introduction/32.external-variables-and-scope.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAXLINE 1000 4 | 5 | int max; 6 | char line[MAXLINE]; 7 | char longest[MAXLINE]; 8 | 9 | int myGetline(void); 10 | void copy(void); 11 | 12 | main() 13 | { 14 | int len; 15 | extern int max; 16 | extern char longest[]; 17 | 18 | max = 0; 19 | while ((len = myGetline()) > 0) 20 | if (len > max) { 21 | max = len; 22 | copy(); 23 | } 24 | 25 | if (max > 0) 26 | printf("%s", longest); 27 | 28 | return 0; 29 | } 30 | 31 | int myGetline(void) 32 | { 33 | int c, i; 34 | extern char line[]; 35 | 36 | for (i = 0; i < MAXLINE - 1 37 | && (c = getchar()) != EOF && c != '\n'; ++i) 38 | line[i] = c; 39 | 40 | if (c == '\n') { 41 | line[i] = c; 42 | ++i; 43 | } 44 | 45 | line[i] = '\0'; 46 | return i; 47 | } 48 | 49 | void copy(void) 50 | { 51 | int i; 52 | extern char line[], longest[]; 53 | 54 | i = 0; 55 | while ((longest[i] = line[i]) != '\0') 56 | ++i; 57 | } 58 | -------------------------------------------------------------------------------- /chapter-1-introduction/33.detab.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | int c, n, i; 6 | int cur; 7 | 8 | n = 8; 9 | 10 | cur = 0; 11 | 12 | while ((c = getchar()) != EOF) { 13 | if (c == '\t') { 14 | for (i = n - cur; i > 0; --i) 15 | putchar(' '); 16 | 17 | cur = 0; 18 | } else { 19 | putchar(c); 20 | cur++; 21 | if (cur > n) 22 | cur = 0; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /chapter-1-introduction/34.entab.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAXLINE 1000 4 | 5 | int myGetline(char line[], int maxline); 6 | 7 | main() 8 | { 9 | int c, len; 10 | int i; 11 | char line[MAXLINE]; 12 | int tabstop; 13 | 14 | tabstop = 8; 15 | while ((len = myGetline(line, MAXLINE)) > 0) { 16 | int spaceCount = 0; 17 | 18 | for (i = 0; i < len; ++i) { 19 | if (line[i] == ' ') 20 | spaceCount++; 21 | else 22 | spaceCount = 0; 23 | 24 | if (spaceCount == tabstop) { 25 | } 26 | } 27 | printf("%s", line); 28 | } 29 | } 30 | 31 | int myGetline(char s[], int lim) 32 | { 33 | int c, i; 34 | 35 | for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) 36 | s[i] = c; 37 | if (c == '\n') { 38 | s[i] = c; 39 | ++i; 40 | } 41 | s[i] = '\0'; 42 | return i; 43 | } 44 | -------------------------------------------------------------------------------- /chapter-1-introduction/35.fold-line.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAXLINE 1000 4 | 5 | int myGetline(char line[], int maxline); 6 | 7 | main() 8 | { 9 | int len; 10 | int lineLenLimit; 11 | char line[MAXLINE], outputLine[MAXLINE]; 12 | int i, j; 13 | int foldCol; 14 | 15 | 16 | lineLenLimit = 10; 17 | 18 | while ((len = myGetline(line, MAXLINE)) > 0) { 19 | for (i = 0; i < len; ++i) { 20 | if (i != 0 && (i + 1) % lineLenLimit == 0) { 21 | for (j = i; j > 0; --j) { 22 | if (line[j] != ' ' && line[j] != '\t') { 23 | foldCol = j; 24 | break; 25 | } 26 | } 27 | 28 | for (j = 0; j < foldCol - i + lineLenLimit; ++j) { 29 | outputLine[j] = line[j + i - lineLenLimit + 1]; 30 | } 31 | outputLine[j] = '\n'; 32 | outputLine[j + 1] = '\0'; 33 | 34 | printf("%s", outputLine); 35 | } else if (i == len - 1) { 36 | for (j = 0; j < i % lineLenLimit; ++j) 37 | outputLine[j] = line[j + i - (i % lineLenLimit)]; 38 | 39 | outputLine[j] = '\0'; 40 | 41 | printf("%s", outputLine); 42 | } 43 | } 44 | } 45 | } 46 | 47 | int myGetline(char s[], int lim) 48 | { 49 | int c, i; 50 | 51 | for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) 52 | s[i] = c; 53 | if (c == '\n') { 54 | s[i] = c; 55 | ++i; 56 | } 57 | s[i] = '\0'; 58 | return i; 59 | } 60 | -------------------------------------------------------------------------------- /chapter-1-introduction/36.remove-comments.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define OUT_COMMENT 0 4 | #define IN_COMMENT 1 5 | #define IN_ONE_LINE_COMMENT 2 6 | 7 | #define OUT_STRING 0 8 | #define IN_STRING 1 9 | 10 | /* 11 | * This is the exercise 1-23 of The C Programming Language 12 | * remove all of the comments in the C program 13 | */ 14 | 15 | main() 16 | { 17 | int c; 18 | int status, stringStatus; 19 | int preChar; 20 | 21 | printf("/*asdqwe*/"); 22 | 23 | status = OUT_COMMENT; 24 | stringStatus = OUT_STRING; 25 | 26 | while((c = getchar()) != EOF) { 27 | /* This is the comment for test */ 28 | if (status == OUT_COMMENT) { 29 | if (stringStatus == OUT_STRING) { 30 | if (c == '"') { 31 | stringStatus = IN_STRING; 32 | putchar(c); 33 | continue; 34 | } 35 | 36 | if (c == '/' && preChar == '/') { 37 | status = IN_ONE_LINE_COMMENT; 38 | preChar = '\n'; 39 | continue; 40 | } else if (c == '/') { 41 | preChar = c; 42 | continue; 43 | } 44 | 45 | if (c == '*' && preChar == '/') { 46 | status = IN_COMMENT; 47 | } else if (preChar == '/') { 48 | putchar('/'); 49 | putchar(c); 50 | } else { 51 | putchar(c); 52 | } 53 | } else { 54 | if (c == '"') { 55 | stringStatus = OUT_STRING; 56 | putchar(c); 57 | } else { 58 | putchar(c); 59 | } 60 | } 61 | } else if (status == IN_ONE_LINE_COMMENT) { 62 | if (c == '\n') { 63 | putchar('\n'); 64 | status = OUT_COMMENT; 65 | } 66 | } else { 67 | if (c == '/' && preChar == '*') { 68 | status = OUT_COMMENT; 69 | preChar = 0; 70 | continue; // comment for test 71 | } 72 | } 73 | preChar = c; 74 | } 75 | 76 | printf("// test one line comment"); 77 | } 78 | -------------------------------------------------------------------------------- /chapter-1-introduction/4.fahrenheit-celsius-table-float.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | float fahr, celsius; 6 | int lower, upper, step; 7 | 8 | lower = 0; /* lower limit of temperature table */ 9 | upper = 300; /* upper limit */ 10 | step = 20; /* step size */ 11 | 12 | fahr = lower; 13 | 14 | printf("Fahrenheit-Celsius table\n"); 15 | while (fahr <= upper) { 16 | celsius = (5.0 / 9.0) * (fahr - 32.0); 17 | printf("%3.0f %6.1f\n", fahr, celsius); 18 | fahr = fahr + step; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /chapter-1-introduction/5.celsius-fahrenheit-table.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | float fahr, celsius; 6 | int lower, upper, step; 7 | 8 | lower = 0; /* lower limit of temperature table */ 9 | upper = 300; /* upper limit */ 10 | step = 20; /* step size */ 11 | 12 | celsius = lower; 13 | 14 | printf("Celsius-Fahrenheit table\n"); 15 | while (celsius <= upper) { 16 | fahr = celsius / (5.0 / 9.0) + 32.0; 17 | printf("%3.0f %6.1f\n", celsius, fahr); 18 | fahr = fahr + step; 19 | celsius += step; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /chapter-1-introduction/6.fahrenheit-celsius-table-for.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | int fahr; 6 | 7 | for (fahr = 0; fahr <= 300; fahr = fahr + 20) 8 | printf("%3d %6.1f\n", fahr, (5.0 / 9.0) * (fahr - 32)); 9 | } 10 | -------------------------------------------------------------------------------- /chapter-1-introduction/7.fahrenheit-celsius-table-reverse.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | int fahr; 6 | 7 | for (fahr = 300; fahr >= 0; fahr = fahr - 20) 8 | printf("%3d %6.1f\n", fahr, (5.0 / 9.0) * (fahr - 32)); 9 | } 10 | -------------------------------------------------------------------------------- /chapter-1-introduction/8.symbolic-constants.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define LOWER 0 4 | #define UPPER 300 5 | #define STEP 20 6 | 7 | main() 8 | { 9 | int fahr; 10 | 11 | for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP) 12 | printf("%3d %6.1f\n", fahr, (5.0 / 9.0) * (fahr - 32)); 13 | } 14 | -------------------------------------------------------------------------------- /chapter-1-introduction/9.file-copying-1st.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* copy input to output; 1st version */ 4 | main() 5 | { 6 | int c; 7 | 8 | c = getchar(); 9 | while (c != EOF) 10 | { 11 | putchar(c); 12 | c = getchar(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /chapter-2-types-operators-expressions/1.ranges-of-variables.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | main() 5 | { 6 | printf("From limits.h:\n"); 7 | printf("CHAR_BIT: %d\n", CHAR_BIT); 8 | printf("CHAR_MAX: %d\n", CHAR_MAX); 9 | printf("CHAR_MIN: %d\n", CHAR_MIN); 10 | printf("INT_MAX: %d\n", INT_MAX); 11 | printf("INT_MIN: %d\n", INT_MIN); 12 | printf("LONG_MAX: %ld\n", LONG_MAX); 13 | printf("LONG_MIN: %ld\n", LONG_MIN); 14 | printf("SCHAR_MAX: %d\n", SCHAR_MAX); 15 | printf("SCHAR_MIN: %d\n", SCHAR_MIN); 16 | printf("SHRT_MAX: %d\n", SHRT_MAX); 17 | printf("SHRT_MIN: %d\n", SHRT_MIN); 18 | printf("UCHAR_MAX: %d\n", UCHAR_MAX); 19 | printf("UINT_MAX: %u\n", UINT_MAX); 20 | printf("ULONG_MAX: %lu\n", ULONG_MAX); 21 | printf("USHRT_MAX: %u\n", USHRT_MAX); 22 | 23 | printf("\nFrom calc:\n"); 24 | 25 | /*signed types*/ 26 | printf("signed char min=%d\n",-(char)((unsigned char) ~0 >> 1)); 27 | printf("signed char max=%d\n",(char)((unsigned char) ~0 >> 1)); 28 | printf("signed int min=%d\n",-(int)((unsigned int) ~0 >> 1)); 29 | printf("signed int max=%d\n",(int)((unsigned int) ~0 >> 1)); 30 | printf("signed short min=%d\n",-(short)((unsigned short) ~0 >> 1)); 31 | printf("signed short max=%d\n",(short)((unsigned short) ~0 >> 1)); 32 | printf("signed long min=%ld\n",-(long)((unsigned long) ~0 >> 1)); 33 | printf("signed long max=%ld\n",(long)((unsigned long) ~0 >> 1)); 34 | 35 | /*unsigned types*/ 36 | printf("unsigned char max=%u\n",((unsigned char) ~0)); 37 | printf("unsigned int max=%u\n",((unsigned int) ~0)); 38 | printf("unsigned long max=%lu\n",((unsigned long) ~0)); 39 | printf("unsigned short max=%u\n",((unsigned short) ~0)); 40 | 41 | } 42 | -------------------------------------------------------------------------------- /chapter-2-types-operators-expressions/10.getbits.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | unsigned getbits(unsigned, int, int); 4 | 5 | main() 6 | { 7 | unsigned a = getbits(255, 3, 4); 8 | printf("%d\n", a); 9 | 10 | unsigned b = getbits(3, 1, 2); 11 | printf("%d\n", b); 12 | } 13 | 14 | unsigned getbits(unsigned x, int p, int n) 15 | { 16 | return (x >> (p+1-n)) & ~(~0 << n); 17 | } 18 | -------------------------------------------------------------------------------- /chapter-2-types-operators-expressions/11.setbits.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int setbits(int, int, int, int); 4 | 5 | main() 6 | { 7 | int a = setbits(255, 0, 4, 0); 8 | printf("%d\n", a); 9 | 10 | int b = setbits(1, 1, 3, 4); 11 | printf("%d\n", b); 12 | 13 | int c = setbits(218, 2, 4, 9); 14 | printf("%d\n", c); 15 | } 16 | 17 | int setbits(int x, int p, int n, int y) 18 | { 19 | x = x & (~((~(~0 << n)) << p)); 20 | y = (y & (~(~0 << n))) << p; 21 | 22 | return x | y; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /chapter-2-types-operators-expressions/12.invert.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int invert(int, int, int); 4 | 5 | main() 6 | { 7 | int a = invert(255, 0, 4); 8 | printf("%d\n", a); 9 | 10 | int b = invert(0, 4, 4); 11 | printf("%d\n", b); 12 | 13 | int c = invert(15, 4, 4); 14 | printf("%d\n", c); 15 | } 16 | 17 | int invert(int x, int p, int n) 18 | { 19 | return x ^ (~(~0 << n) << p); 20 | } 21 | 22 | -------------------------------------------------------------------------------- /chapter-2-types-operators-expressions/13.rightrot.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | unsigned rightrot(unsigned, unsigned); 4 | 5 | main() 6 | { 7 | int a = rightrot(255, 32); 8 | printf("%d\n", a); 9 | 10 | int b = rightrot(1, 30); 11 | printf("%d\n", b); 12 | } 13 | 14 | unsigned rightrot(unsigned x, unsigned n) 15 | { 16 | while (n-- > 0) { 17 | if (x & 1 == 1) { 18 | x = (x >> 1) | ~(~0U >> 1); 19 | } else { 20 | x = x >> 1; 21 | } 22 | } 23 | 24 | return x; 25 | } 26 | 27 | -------------------------------------------------------------------------------- /chapter-2-types-operators-expressions/14.bitcount.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int bitcount(unsigned); 4 | 5 | main() 6 | { 7 | printf("%d\n", bitcount(255)); 8 | printf("%d\n", bitcount(15)); 9 | printf("%d\n", bitcount(1)); 10 | printf("%d\n", bitcount(0)); 11 | printf("%d\n", bitcount(~0U)); 12 | } 13 | 14 | int bitcount(unsigned x) 15 | { 16 | int b; 17 | for (b = 0; x != 0; x >>= 1) 18 | if (x & 01) 19 | b++; 20 | 21 | return b; 22 | } 23 | -------------------------------------------------------------------------------- /chapter-2-types-operators-expressions/15.bitcount2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int bitcount(unsigned); 4 | 5 | main() 6 | { 7 | printf("%d\n", bitcount(255)); 8 | printf("%d\n", bitcount(15)); 9 | printf("%d\n", bitcount(1)); 10 | printf("%d\n", bitcount(0)); 11 | printf("%d\n", bitcount(~0U)); 12 | } 13 | 14 | int bitcount(unsigned x) 15 | { 16 | int b = 1; 17 | 18 | if (x == 0) 19 | b--; 20 | 21 | while (x &= (x-1)) 22 | b++; 23 | 24 | 25 | return b; 26 | } 27 | -------------------------------------------------------------------------------- /chapter-2-types-operators-expressions/16.lower2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int lower(int); 4 | 5 | main() 6 | { 7 | printf("%c\n", lower('S')); 8 | printf("%c\n", lower('A')); 9 | printf("%c\n", lower('Z')); 10 | printf("%c\n", lower('a')); 11 | } 12 | 13 | int lower(int c) 14 | { 15 | return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c; 16 | } 17 | 18 | -------------------------------------------------------------------------------- /chapter-2-types-operators-expressions/2.loop-without-logical-operators.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAXLINE 1024 4 | 5 | int myGetline(char line[], int maxline); 6 | int myGetlineV1(char line[], int maxline); 7 | 8 | main() 9 | { 10 | int len; 11 | char line[MAXLINE]; 12 | 13 | while ((len = myGetlineV1(line, MAXLINE)) > 0) { 14 | printf("%s", line); 15 | } 16 | 17 | return 0; 18 | } 19 | 20 | int myGetline(char s[], int lim) 21 | { 22 | int c, i; 23 | 24 | for (i = 0; i < lim - 1 && (c = getchar()) != '\n' && c != EOF; ++i) 25 | s[i] = c; 26 | if (c == '\n') { 27 | s[i] = c; 28 | ++i; 29 | } 30 | s[i] = '\0'; 31 | return i; 32 | } 33 | 34 | int myGetlineV1(char s[], int lim) 35 | { 36 | int c, i; 37 | 38 | for (i = 0; i < lim - 1; ++i) { 39 | if ((c = getchar()) == '\n') 40 | break; 41 | if (c == EOF) 42 | break; 43 | 44 | s[i] = c; 45 | } 46 | 47 | if (c == '\n') { 48 | s[i] = c; 49 | ++i; 50 | } 51 | s[i] = '\0'; 52 | return i; 53 | } 54 | -------------------------------------------------------------------------------- /chapter-2-types-operators-expressions/3.atoi.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int atoi(char[]); 4 | 5 | main() 6 | { 7 | int a = atoi("1234567890"); 8 | printf("%d\n", a); 9 | a = atoi("1234abc567890"); 10 | printf("%d\n", a); 11 | } 12 | 13 | int atoi(char s[]) 14 | { 15 | int i, n; 16 | n = 0; 17 | for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i) 18 | n = 10 * n + (s[i] - '0'); 19 | return n; 20 | } 21 | -------------------------------------------------------------------------------- /chapter-2-types-operators-expressions/4.lower.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int lower(int); 4 | 5 | main() 6 | { 7 | printf("%c\n", lower('S')); 8 | printf("%c\n", lower('A')); 9 | printf("%c\n", lower('Z')); 10 | printf("%c\n", lower('a')); 11 | } 12 | 13 | int lower(int c) 14 | { 15 | if (c >= 'A' && c <= 'Z') 16 | return c + 'a' - 'A'; 17 | else 18 | return c; 19 | } 20 | -------------------------------------------------------------------------------- /chapter-2-types-operators-expressions/5.htio.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int htoi(char[]); 4 | 5 | main() 6 | { 7 | int n = htoi("0x123abc"); 8 | printf("%d\n", n); 9 | n = htoi("0X123abc"); 10 | printf("%d\n", n); 11 | n = htoi("123abc"); 12 | printf("%d\n", n); 13 | n = htoi("FF"); 14 | printf("%d\n", n); 15 | n = htoi("1F"); 16 | printf("%d\n", n); 17 | n = htoi("D"); 18 | printf("%d\n", n); 19 | n = htoi("3"); 20 | printf("%d\n", n); 21 | n = htoi("3FQWE"); 22 | printf("%d\n", n); 23 | } 24 | 25 | int htoi(char s[]) 26 | { 27 | int i, n; 28 | n = 0; 29 | for (i = 0; ; ++i) { 30 | if (s[i] == '0' && (s[i+1] == 'x' || s[i+1] == 'X')) { 31 | i++; 32 | continue; 33 | } 34 | 35 | if (s[i] >= '0' && s[i] <= '9') { 36 | n = 16 * n + (s[i] - '0'); 37 | } else if (s[i] >= 'a' && s[i] <= 'f') { 38 | n = 16 * n + (s[i] - 'a' + 10); 39 | } else if (s[i] >= 'A' && s[i] <= 'F') { 40 | n = 16 * n + (s[i] - 'A' + 10); 41 | } else { 42 | break; 43 | } 44 | } 45 | return n; 46 | } 47 | -------------------------------------------------------------------------------- /chapter-2-types-operators-expressions/6.squeeze.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void squeeze(char[], int); 4 | 5 | main() 6 | { 7 | char s[] = "test"; 8 | squeeze(s, 't'); 9 | printf("%s\n", s); 10 | } 11 | 12 | void squeeze(char s[], int c) 13 | { 14 | int i ,j; 15 | 16 | for (i = j = 0; s[i] != '\0'; i++) 17 | if (s[i] != c) 18 | s[j++] = s[i]; 19 | 20 | s[j] = '\0'; 21 | } 22 | -------------------------------------------------------------------------------- /chapter-2-types-operators-expressions/7.strcat.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void strcat(char s[], char t[]); 4 | 5 | main() 6 | { 7 | } 8 | 9 | void strcat(char s[], cahr t[]) 10 | { 11 | int i, j; 12 | 13 | i = j = 0; 14 | while (s[i] != '\0') 15 | i++; 16 | while ((s[i++] = t[j++]) != '\0') 17 | ; 18 | } 19 | -------------------------------------------------------------------------------- /chapter-2-types-operators-expressions/8.squeeze2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void squeeze(char[], char[]); 4 | 5 | main() 6 | { 7 | char s[] = "test"; 8 | char t[] = "te"; 9 | squeeze(s, t); 10 | printf("%s\n", s); 11 | 12 | char s1[] = "test"; 13 | char t1[] = "st"; 14 | squeeze(s1, t1); 15 | printf("%s\n", s1); 16 | 17 | char s2[] = "test"; 18 | char t2[] = "sta"; 19 | squeeze(s2, t2); 20 | printf("%s\n", s2); 21 | 22 | char s3[] = "test"; 23 | char t3[] = "test"; 24 | squeeze(s3, t3); 25 | printf("%s\n", s3); 26 | 27 | char s4[] = "test"; 28 | char t4[] = ""; 29 | squeeze(s4, t4); 30 | printf("%s\n", s4); 31 | } 32 | 33 | void squeeze(char s[], char t[]) 34 | { 35 | if (t[0] == '\0') 36 | return; 37 | 38 | int i ,j, k; 39 | int same; 40 | 41 | for (i = j = 0; s[i] != '\0'; i++) { 42 | same = 1; 43 | 44 | for (k = 0; t[k] != '\0'; k++) { 45 | if (s[i+k] == '\0') { 46 | same = 0; 47 | break; 48 | } 49 | 50 | 51 | if (t[k] != s[i+k]) { 52 | same = 0; 53 | break; 54 | } 55 | } 56 | 57 | if (same == 1) { 58 | i += k - 1; 59 | } else { 60 | s[j++] = s[i]; 61 | } 62 | } 63 | 64 | s[j] = '\0'; 65 | } 66 | 67 | -------------------------------------------------------------------------------- /chapter-2-types-operators-expressions/9.any.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int any(char[], char[]); 4 | 5 | main() 6 | { 7 | int p; 8 | p = any("test", "test"); 9 | printf("p: %d\n", p); 10 | 11 | p = any("test", "es"); 12 | printf("p: %d\n", p); 13 | 14 | p = any("test", "s1"); 15 | printf("p: %d\n", p); 16 | 17 | p = any("test", "123"); 18 | printf("p: %d\n", p); 19 | } 20 | 21 | int any(char s1[], char s2[]) 22 | { 23 | int i, j; 24 | int result = -1; 25 | 26 | for(i = 0; s1[i] != '\0'; i++) { 27 | for (j = 0; s2[j] != '\0'; j++) { 28 | if (s1[i] == s2[j]) { 29 | result = i; 30 | break; 31 | } 32 | } 33 | 34 | if (result != -1) 35 | break; 36 | } 37 | 38 | return result; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /chapter-3-control-flow/01.binsearch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | #define ARRAY_LEN 500000 6 | 7 | int binsearch(int, int[], int); 8 | int binsearchFast(int, int[], int); 9 | 10 | main() 11 | { 12 | clock_t start, finish; 13 | int i, v[ARRAY_LEN]; 14 | for (i = 0; i < ARRAY_LEN; i++) 15 | v[i] = i; 16 | 17 | start = clock(); 18 | int p; 19 | for (i = 0; i < ARRAY_LEN; i++) { 20 | p = binsearch(i, v, ARRAY_LEN); 21 | //printf("%d at %d\n", i, p); 22 | } 23 | finish = clock(); 24 | 25 | printf("binsearch duration: %f\n", ((double)(finish - start)) / CLOCKS_PER_SEC); 26 | 27 | //printf("binsearchFast:\n"); 28 | 29 | start = clock(); 30 | for (i = 0; i < ARRAY_LEN; i++) { 31 | p = binsearchFast(i, v, ARRAY_LEN); 32 | //printf("%d at %d\n", i, p); 33 | } 34 | finish = clock(); 35 | printf("binsearchFast duration: %f\n", ((double)(finish - start)) / CLOCKS_PER_SEC); 36 | 37 | for (i = -10000; i < ARRAY_LEN; i++) { 38 | p = binsearchFast(i, v, ARRAY_LEN); 39 | if (i < 0 && p != -1) 40 | break; 41 | else if (i >= 0 && p != i) 42 | break; 43 | } 44 | printf("i: %d\n", i); 45 | } 46 | 47 | /* binsearch: find x in v[0] <= v[1] <= ... v[n-1] */ 48 | int binsearch(int x, int v[], int n) 49 | { 50 | int low, high, mid; 51 | 52 | low = 0; 53 | high = n - 1; 54 | while (low <= high) { 55 | mid = (low + high) / 2; 56 | if (x < v[mid]) 57 | high = mid - 1; 58 | else if (x > v[mid]) 59 | low = mid + 1; 60 | else 61 | return mid; 62 | } 63 | return -1; 64 | } 65 | 66 | int binsearchFast(int x, int v[], int n) 67 | { 68 | int low, high, mid; 69 | 70 | low = 0; 71 | high = n - 1; 72 | while (low <= high) { 73 | mid = (low + high) / 2; 74 | 75 | if (x <= v[mid]) 76 | high = mid - 1; 77 | else 78 | low = mid + 1; 79 | } 80 | 81 | if (x == v[mid]) 82 | return mid; 83 | else if (x > v[mid]) 84 | mid += 1; 85 | else 86 | mid -= 1; 87 | 88 | if (mid < 0 || mid > n - 1) 89 | return -1; 90 | else 91 | return mid; 92 | } 93 | -------------------------------------------------------------------------------- /chapter-3-control-flow/02.switch.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | int c, i, nwhite, nother, ndigit[10]; 6 | 7 | nwhite = nother = 0; 8 | for (i = 0; i < 10; i++) 9 | ndigit[i] = 0; 10 | 11 | while ((c = getchar()) != EOF) { 12 | switch(c) { 13 | case '0': case '1': case '2': case '3': case '4': 14 | case '5': case '6': case '7': case '8': case '9': 15 | ndigit[c-'0']++; 16 | break; 17 | case ' ': 18 | case '\n': 19 | case '\t': 20 | nwhite++; 21 | break; 22 | default: 23 | nother++; 24 | break; 25 | } 26 | } 27 | printf("digits = "); 28 | for (i = 0; i < 10; i++) 29 | printf(" %d", ndigit[i]); 30 | printf(", white space = %d, other = %d\n", 31 | nwhite, nother); 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /chapter-3-control-flow/03.escape.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAX_LEN 1000 4 | 5 | void escape(char[], char[]); 6 | 7 | main() 8 | { 9 | char t[] = "Hello\tWorld\r\n\v"; 10 | printf("%s\n", t); 11 | char s[MAX_LEN]; 12 | escape(s, t); 13 | printf("%s\n", s); 14 | } 15 | 16 | void escape(char s[], char t[]) 17 | { 18 | int i, j, n; 19 | for (i = 0, j = 0; t[j] != '\0'; i++, j++) { 20 | switch(t[j]) { 21 | case '\a': 22 | s[i++] = '\\'; 23 | n = 'a'; 24 | break; 25 | case '\b': 26 | s[i++] = '\\'; 27 | n = 'b'; 28 | break; 29 | case '\f': 30 | s[i++] = '\\'; 31 | n = 'f'; 32 | break; 33 | case '\n': 34 | s[i++] = '\\'; 35 | n = 'n'; 36 | break; 37 | case '\r': 38 | s[i++] = '\\'; 39 | n = 'r'; 40 | break; 41 | case '\t': 42 | s[i++] = '\\'; 43 | n = 't'; 44 | break; 45 | case '\v': 46 | s[i++] = '\\'; 47 | n = 'v'; 48 | break; 49 | default: 50 | n = t[j]; 51 | break; 52 | } 53 | s[i] = n; 54 | } 55 | s[i] = '\0'; 56 | } 57 | -------------------------------------------------------------------------------- /chapter-3-control-flow/04.unescape.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAX_LEN 1024 4 | 5 | void unescape(char[], char[]); 6 | 7 | main() 8 | { 9 | char t[] = "Hello\\tWorld!!!\\r\\nEOF\\v"; 10 | printf("%s\n", t); 11 | char s[MAX_LEN] = ""; 12 | unescape(s, t); 13 | printf("%s\n", s); 14 | } 15 | 16 | void unescape(char s[], char t[]) 17 | { 18 | int i, j, n; 19 | 20 | for (i = 0, j = 0; t[j] != '\0'; i++, j++) { 21 | if (t[j] == '\\' && t[j+1] != '\0') { 22 | j++; 23 | 24 | switch(t[j]) { 25 | case 'a': 26 | s[i] = '\a'; 27 | break; 28 | case 'b': 29 | s[i] = '\b'; 30 | break; 31 | case 'f': 32 | s[i] = '\f'; 33 | break; 34 | case 'n': 35 | s[i] = '\n'; 36 | break; 37 | case 'r': 38 | s[i] = '\r'; 39 | break; 40 | case 't': 41 | s[i] = '\t'; 42 | break; 43 | case 'v': 44 | s[i] = '\v'; 45 | break; 46 | default: 47 | s[i++] = '\\'; 48 | s[i] = t[j]; 49 | break; 50 | } 51 | } else { 52 | s[i] = t[j]; 53 | } 54 | } 55 | 56 | s[i] = '\0'; 57 | } 58 | 59 | -------------------------------------------------------------------------------- /chapter-3-control-flow/05.atoi.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | main() 5 | { 6 | printf("%d\n", atoi("123")); 7 | printf("%d\n", atoi("+1")); 8 | printf("%d\n", atoi("-0")); 9 | printf("%d\n", atoi("-123")); 10 | printf("%d\n", atoi("asd345")); 11 | printf("%d\n", atoi("789asd345")); 12 | } 13 | 14 | int atoi(char s[]) 15 | { 16 | int i, n, sign; 17 | 18 | for (i = 0; isspace(s[i]); i++) 19 | ; 20 | 21 | sign = (s[i] == '-') ? -1 : 1; 22 | 23 | if (s[i] == '+' || s[i] == '-') 24 | i++; 25 | 26 | for (n = 0; isdigit(s[i]); i++) 27 | n = 10 * n + (s[i] - '0'); 28 | 29 | return sign * n; 30 | } 31 | 32 | -------------------------------------------------------------------------------- /chapter-3-control-flow/06.shellsort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void shellsort(int [], int); 4 | void printArr(int [], int); 5 | 6 | main() 7 | { 8 | int len = 12; 9 | int v[] = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; 10 | printArr(v, len); 11 | shellsort(v, len); 12 | printArr(v, len); 13 | } 14 | 15 | // sort v[0]...v[n-1] into increasing order 16 | void shellsort(int v[], int n) 17 | { 18 | int gap, i, j, temp; 19 | 20 | for (gap = n / 2; gap > 0; gap /= 2) 21 | for (i = gap; i < n; i++) 22 | for (j = i - gap; j >= 0 && v[j] > v [j + gap]; j -= gap) { 23 | printf("gap: %d, i: %d, j: %d, j+gap: %d\n", gap, i, j, j+gap); 24 | temp = v[j]; 25 | v[j] = v[j+gap]; 26 | v[j+gap] = temp; 27 | } 28 | } 29 | 30 | void printArr(int v[], int len) 31 | { 32 | int i; 33 | for (i = 0; i < len; i++) 34 | printf("%d ", v[i]); 35 | printf("\n"); 36 | } 37 | -------------------------------------------------------------------------------- /chapter-3-control-flow/07.reverse.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void reverse(char[]); 5 | 6 | main() 7 | { 8 | char a[] = "Hello, World!"; 9 | reverse(a); 10 | printf("%s\n", a); 11 | } 12 | 13 | void reverse(char s[]) 14 | { 15 | int c, i, j; 16 | 17 | for (i = 0, j = strlen(s) - 1; i < j; i++, j--) { 18 | c = s[i]; 19 | s[i] = s[j]; 20 | s[j] = c; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /chapter-3-control-flow/08.expand.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAX_LEN 1024 4 | 5 | void expand(char s1[], char s2[]); 6 | 7 | main() 8 | { 9 | char s1[] = "-a-z-A-Z-0-9-asd-5-5-5-9a-ZZ-A-G-N-T-Z"; 10 | char s2[MAX_LEN]; 11 | expand(s1, s2); 12 | printf("%s\n", s2); 13 | 14 | char s[] = "-a-z 0-9 a-d-f -0-2 some text 1-1 WITH CAPITALS! 0-0 5-3 -"; 15 | char t[MAX_LEN]; 16 | expand(s, t); 17 | printf("%s\n", t); 18 | } 19 | 20 | void expand(char s1[], char s2[]) 21 | { 22 | int i, j, k; 23 | 24 | for (i = 0, j = 0; s1[i] != '\0'; i++) { 25 | if (s1[i] == '-' && i > 0 && s1[i+1] != '\0') { 26 | int p = s1[i-1]; 27 | int n = s1[i+1]; 28 | if (p < n && 29 | ((p >= 'a' && n <= 'z') || (p >= 'A' && n <= 'Z') || (p >= '0' && n <= '9')) 30 | ) { 31 | for (k = p + 1; k < n; k++) 32 | s2[j++] = k; 33 | } else { 34 | s2[j++] = s1[i]; 35 | } 36 | } else { 37 | s2[j++] = s1[i]; 38 | } 39 | } 40 | 41 | s2[j] = '\0'; 42 | } 43 | -------------------------------------------------------------------------------- /chapter-3-control-flow/09.itoa.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void itoa(int n, char s[]); 6 | void reverse(char[]); 7 | 8 | 9 | main() 10 | { 11 | int a = 0; 12 | char s[10]; 13 | itoa(a, s); 14 | printf("%s\n", s); 15 | 16 | a = INT_MIN; 17 | itoa(a, s); 18 | printf("%s\n", s); 19 | 20 | a = INT_MAX; 21 | itoa(a, s); 22 | printf("%s\n", s); 23 | } 24 | 25 | void itoa(int n, char s[]) 26 | { 27 | int i, sign; 28 | int preN = n; 29 | int nIsMinNagetive = n != 0 && n == -n; 30 | 31 | if ((sign = n) < 0) { 32 | if (nIsMinNagetive) { 33 | n += 1; 34 | n = -n; 35 | } else { 36 | n = -n; 37 | } 38 | } 39 | 40 | i = 0; 41 | do { 42 | s[i++] = n % 10 + '0'; 43 | } while ((n /= 10) > 0); 44 | 45 | if (sign < 0) 46 | s[i++] = '-'; 47 | 48 | s[i] = '\0'; 49 | reverse(s); 50 | 51 | if (nIsMinNagetive) 52 | s[strlen(s) - 1] += 1; 53 | } 54 | 55 | void reverse(char s[]) 56 | { 57 | int c, i, j; 58 | 59 | for (i = 0, j = strlen(s) - 1; i < j; i++, j--) { 60 | c = s[i]; 61 | s[i] = s[j]; 62 | s[j] = c; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /chapter-3-control-flow/10.itob.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define MAX_LEN 1024 7 | 8 | void itob(int n, char s[], int b); 9 | void itob2(int n, char s[], int b); 10 | void reverse(char[]); 11 | 12 | main() 13 | { 14 | int n = 255; 15 | char s[MAX_LEN]; 16 | itob(n, s, 16); 17 | printf("n: %d, s: %s\n", n, s); 18 | 19 | n = INT_MAX; 20 | itob(n, s, 16); 21 | printf("n: %d, s: %s\n", n, s); 22 | 23 | n = 2048; 24 | itob(n, s, 2); 25 | printf("n: %d, s: %s\n", n, s); 26 | 27 | n = 2048; 28 | itob(n, s, 8); 29 | printf("n: %d, s: %s\n", n, s); 30 | 31 | n = INT_MIN; 32 | itob(n, s, 16); 33 | printf("n: %d, s: %s\n", n, s); 34 | } 35 | 36 | void itob(int n, char s[], int b) 37 | { 38 | int i; 39 | int sign = n; 40 | 41 | i = 0; 42 | do { 43 | char c; 44 | int m = abs(n % b); 45 | if (m < 10) 46 | c = m + '0'; 47 | else 48 | c = m - 10 + 'a'; 49 | s[i++] = c; 50 | } while (n /= b); 51 | 52 | if (sign < 0) 53 | s[i++] = '-'; 54 | 55 | s[i] = '\0'; 56 | reverse(s); 57 | } 58 | 59 | void reverse(char s[]) 60 | { 61 | int c, i, j; 62 | 63 | for (i = 0, j = strlen(s) - 1; i < j; i++, j--) { 64 | c = s[i]; 65 | s[i] = s[j]; 66 | s[j] = c; 67 | } 68 | } 69 | 70 | -------------------------------------------------------------------------------- /chapter-3-control-flow/11.itoa.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define MAX_LEN 1024 7 | 8 | void itoa(int n, char s[], int minWidth); 9 | void reverse(char[]); 10 | 11 | 12 | main() 13 | { 14 | int a = 0; 15 | char s[MAX_LEN]; 16 | itoa(a, s, 5); 17 | printf("a: %d, %s\n", a, s); 18 | 19 | a = INT_MIN; 20 | itoa(a, s, 20); 21 | printf("INT_MIN: %d, %s\n", a, s); 22 | 23 | a = INT_MAX; 24 | itoa(a, s, 15); 25 | printf("INT_MAX: %d, %s\n", a, s); 26 | 27 | a = 1234567890; 28 | itoa(a, s, 5); 29 | printf("a: %d, %s\n", a, s); 30 | } 31 | 32 | void itoa(int n, char s[], int minWidth) 33 | { 34 | int i; 35 | int sign = n; 36 | 37 | i = 0; 38 | do { 39 | s[i++] = abs(n % 10) + '0'; 40 | } while (n /= 10); 41 | 42 | if (sign < 0) 43 | s[i++] = '-'; 44 | 45 | int needSpace = minWidth - strlen(s); 46 | while (needSpace-- > 0) { 47 | s[i++] = ' '; 48 | } 49 | 50 | s[i] = '\0'; 51 | reverse(s); 52 | } 53 | 54 | void reverse(char s[]) 55 | { 56 | int c, i, j; 57 | 58 | for (i = 0, j = strlen(s) - 1; i < j; i++, j--) { 59 | c = s[i]; 60 | s[i] = s[j]; 61 | s[j] = c; 62 | } 63 | } 64 | 65 | -------------------------------------------------------------------------------- /chapter-3-control-flow/12.trim.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int trim(char[]); 5 | 6 | main() 7 | { 8 | char s[1024] = "Hello, World "; 9 | trim(s); 10 | printf("%sEOL\n", s); 11 | 12 | s[0] = '\0'; 13 | trim(s); 14 | printf("%sEOL\n", s); 15 | 16 | s[0] = ' ', s[1] = ' ', s[2] = '\0'; 17 | trim(s); 18 | printf("%sEOL\n", s); 19 | 20 | char a[1024] = "Hello, World 123"; 21 | trim(a); 22 | printf("%sEOL\n", a); 23 | } 24 | 25 | int trim(char s[]) 26 | { 27 | int n; 28 | 29 | for (n = strlen(s) - 1; n >= 0; n--) 30 | if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n') 31 | break; 32 | 33 | s[n+1] = '\0'; 34 | return n; 35 | } 36 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/1.simple-grep.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAXLINE 1000 4 | 5 | int mygetline(char line[], int max); 6 | int strindex(char source[], char searchfor[]); 7 | 8 | char pattern[] = "ould"; 9 | 10 | main() 11 | { 12 | char line[MAXLINE]; 13 | int found = 0; 14 | 15 | while (mygetline(line, MAXLINE) > 0) 16 | if (strindex(line, pattern) >= 0) { 17 | printf("%s", line); 18 | found++; 19 | } 20 | return found; 21 | } 22 | 23 | int mygetline(char s[], int lim) 24 | { 25 | int c, i; 26 | i =0; 27 | while (--lim > 0 && (c = getchar()) != EOF && c != '\n') 28 | s[i++] = c; 29 | if (c == '\n') 30 | s[i++] = c; 31 | s[i] = '\0'; 32 | return i; 33 | } 34 | 35 | int strindex(char s[], char t[]) 36 | { 37 | int i, j, k; 38 | 39 | for (i = 0; s[i] != '\0'; i++) { 40 | for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++,k++) 41 | ; 42 | if (k > 0 && t[k] == '\0') 43 | return i; 44 | } 45 | return -1; 46 | } 47 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/10.reverse.recursive.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void reverse(char [], int, int); 5 | void swap(char s[], int i, int j); 6 | 7 | int main() 8 | { 9 | char s[] = "Hello, World!!!"; 10 | reverse(s, 0, strlen(s) - 1); 11 | printf("%s", s); 12 | } 13 | 14 | void reverse(char s[], int left, int right) 15 | { 16 | if (left >= right) 17 | return; 18 | 19 | swap(s, left, right); 20 | reverse(s, ++left, --right); 21 | } 22 | 23 | void swap(char s[], int i, int j) 24 | { 25 | char temp = s[j]; 26 | s[j] = s[i]; 27 | s[i] = temp; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/11.swap-macro.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define swap(t, x, y) { t temp = x; x = y; y = temp; } 4 | 5 | int main() 6 | { 7 | int x, y; 8 | x = 1; 9 | y = 2; 10 | swap(int, x, y); 11 | printf("%d, %d\n", x, y); 12 | 13 | double a, b; 14 | a = 1.2; 15 | b = -3.9; 16 | swap(double, a, b); 17 | printf("%g, %g\n", a, b); 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/12.conditional-inclusion.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define SYSTEM 1 4 | 5 | #define BSD 0 6 | #define SYSV 1 7 | #define MSDOC 2 8 | 9 | #ifndef HDR 10 | #if SYSTEM == BSD 11 | #define HDR "bsd.h" 12 | #elif SYSTEM == SYSV 13 | #define HDR "sysv.h" 14 | #elif SYSTEM == MSDOC 15 | #define HDR "msdos.h" 16 | #else 17 | #define HDR "default.h" 18 | #endif 19 | 20 | #include HDR 21 | #endif 22 | 23 | int main() 24 | { 25 | printf("%s\n", OS); 26 | } 27 | 28 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/2.strrindex.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAXLINE 1000 5 | 6 | int mygetline(char line[], int max); 7 | int strrindex(char source[], char searchfor[]); 8 | 9 | char pattern[] = "ould"; 10 | 11 | main() 12 | { 13 | char line[MAXLINE]; 14 | int found = 0; 15 | int p; 16 | 17 | while (mygetline(line, MAXLINE) > 0) { 18 | p = strrindex(line, pattern); 19 | if (p >= 0) { 20 | printf("%s", line); 21 | found++; 22 | } 23 | } 24 | return found; 25 | } 26 | 27 | int mygetline(char s[], int lim) 28 | { 29 | int c, i; 30 | i =0; 31 | while (--lim > 0 && (c = getchar()) != EOF && c != '\n') 32 | s[i++] = c; 33 | if (c == '\n') 34 | s[i++] = c; 35 | s[i] = '\0'; 36 | return i; 37 | } 38 | 39 | int strrindex(char s[], char t[]) 40 | { 41 | int i, j, k; 42 | 43 | for (i = strlen(s) - 2; i > 0; i--) { 44 | for (j = i, k = strlen(t) - 1; j > 0 && k > 0 && s[j] == t[k]; j--, k--) 45 | ; 46 | 47 | if (k == 0) 48 | return j; 49 | } 50 | return -1; 51 | } 52 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/3.atof-test.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAXLINE 100 4 | 5 | // compile with atof.c, mygetline.c 6 | main() 7 | { 8 | double sum, atof(char []); 9 | char line[MAXLINE]; 10 | int mygetline(char line[], int max); 11 | 12 | sum = 0; 13 | while (mygetline(line, MAXLINE) > 0) 14 | printf("\t%g\n", sum += atof(line)); 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/4.reverse-polish-calculator.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include // for atof() 4 | #include // for fmod() 5 | #include "calc.h" 6 | 7 | #define MAXOP 100 // max size of operand or operator 8 | #define MAX_VAR_LEN 26 // max size of array for variables 9 | 10 | void mathfunc(char[]); 11 | void setVar(double, double); 12 | void getVar(char[]); 13 | 14 | double variables[MAX_VAR_LEN]; 15 | int variableFlags[MAX_VAR_LEN]; // if [0] is 0, means 'a' not set, if [0] is 1, means 'a' set 16 | 17 | // compile with stack.c, getop.c, getch.c 18 | main() 19 | { 20 | int type; 21 | double op2; 22 | char s[MAXOP]; 23 | 24 | int i; 25 | 26 | for (i = 0; i < MAX_VAR_LEN; i++) 27 | variableFlags[i] = 0; 28 | 29 | while ((type = getop(s)) != EOF) { 30 | switch(type) { 31 | case NUMBER: 32 | push(atof(s)); 33 | break; 34 | case VAR: 35 | getVar(s); 36 | break; 37 | case FUNC: 38 | mathfunc(s); 39 | break; 40 | case '+': 41 | push(pop() + pop()); 42 | break; 43 | case '*': 44 | push(pop() * pop()); 45 | break; 46 | case '-': 47 | op2 = pop(); 48 | push(pop() - op2); 49 | break; 50 | case '/': 51 | op2 = pop(); 52 | if (op2 != 0.0) 53 | push(pop() / op2); 54 | else 55 | printf("error: zero divisor\n"); 56 | break; 57 | case '%': 58 | op2 = pop(); 59 | if (op2 == 0.0) 60 | printf("error: can not mod 0\n"); 61 | else 62 | push(fmod(pop(), op2)); 63 | break; 64 | case '=': 65 | op2 = pop(); 66 | setVar(pop(), op2); 67 | break; 68 | case '\n': 69 | printf("\t%.8g\n", pop()); 70 | break; 71 | default: 72 | printf("error: unknown command %s\n", s); 73 | break; 74 | } 75 | } 76 | return 0; 77 | } 78 | 79 | void mathfunc(char s[]) 80 | { 81 | int index; 82 | if (0 == strrindex(s, "sin")) { 83 | push(sin(pop())); 84 | return; 85 | } 86 | 87 | if (0 == strrindex(s, "exp")) { 88 | push(exp(pop())); 89 | return; 90 | } 91 | 92 | if (0 == strrindex(s, "pow")) { 93 | double ey = pop(); 94 | push(pow(pop(), ey)); 95 | return; 96 | } 97 | 98 | printf("error: unknown func %s\n", s); 99 | return; 100 | } 101 | 102 | void setVar(double varIndex, double value) 103 | { 104 | int index = (int)varIndex; 105 | if (index < 0 || index > MAX_VAR_LEN) { 106 | printf("error: cannot set variable, invalid variable: %c\n", index + 'a'); 107 | return; 108 | } 109 | 110 | variables[index] = value; 111 | variableFlags[index] = 1; 112 | 113 | push(value); // to show result 114 | 115 | return; 116 | } 117 | 118 | void getVar(char s[]) 119 | { 120 | if (strlen(s) != 1 && s[0] != 0) { 121 | // if variable is 'a', s[0] == 0, strlen(s) == 0 122 | printf("error: cannot get variable, invalid variable: %s\n", s); 123 | return; 124 | } 125 | 126 | double value = atof(s); 127 | int index = (int)value; 128 | if (variableFlags[index] == 0) 129 | push(value); 130 | else 131 | push(variables[index]); 132 | 133 | return; 134 | } 135 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/5.getop-with-static.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define BUFSIZE 100 5 | #define MAX_LEN 1024 6 | #define NUMBER '0' 7 | 8 | int getop(char []); 9 | 10 | int main() 11 | { 12 | while (1) { 13 | char s[MAX_LEN]; 14 | int op = getop(s); 15 | printf("op: %c\n", op); 16 | } 17 | } 18 | 19 | int getop(char s[]) 20 | { 21 | static int buffer = EOF; 22 | printf("buffer: %d\n", buffer); 23 | int i, c; 24 | 25 | while ((s[0] = c = (buffer == EOF ? getchar() : buffer)) == ' ' || c == '\t') 26 | ; 27 | 28 | s[1] = '\0'; 29 | if (!isdigit(c) && c != '.') 30 | return c; 31 | i = 0; 32 | if (isdigit(c)) 33 | while (isdigit(s[++i] = c = (buffer == EOF ? getchar() : buffer))) 34 | ; 35 | 36 | if (c == '.') 37 | while (isdigit(s[++i] = c = (buffer == EOF ? getchar() : buffer))) 38 | ; 39 | s[i] = '\0'; 40 | if (c != EOF) { 41 | if (buffer != EOF) 42 | printf("getop: cannot ungetch more char\n"); 43 | else 44 | buffer = c; 45 | } 46 | return NUMBER; 47 | } 48 | 49 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/6.register-variable.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define LOOP_COUNT 1e8 5 | 6 | void withRegister(void); 7 | void withoutRegister(void); 8 | 9 | int main() 10 | { 11 | clock_t start, finish; 12 | start = clock(); 13 | withRegister(); 14 | finish = clock(); 15 | printf("withRegister duration: %f\n", ((double)(finish - start)) / CLOCKS_PER_SEC); 16 | 17 | start = clock(); 18 | withoutRegister(); 19 | finish = clock(); 20 | printf("withoutRegister duration: %f\n", ((double)(finish - start)) / CLOCKS_PER_SEC); 21 | } 22 | 23 | void withRegister(void) 24 | { 25 | register int i; 26 | for (i = 0; i < LOOP_COUNT; i++) 27 | ; 28 | 29 | } 30 | 31 | void withoutRegister(void) 32 | { 33 | int i; 34 | for (i = 0; i < LOOP_COUNT; i++) 35 | ; 36 | } 37 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/7.printd.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void printd(int n); 4 | 5 | int main() 6 | { 7 | printd(-123456); 8 | } 9 | 10 | void printd(int n) 11 | { 12 | if (n < 0) { 13 | putchar('-'); 14 | n = -n; 15 | } 16 | if (n / 10) 17 | printd(n / 10); 18 | putchar(n % 10 + '0'); 19 | } 20 | 21 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/8.qsort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define ARR_LEN 7 4 | 5 | void qsort(int v[], int left, int right); 6 | void printArr(int v[], int len); 7 | 8 | int main() 9 | { 10 | int i; 11 | int v[ARR_LEN] = { 4, 3, 1, 7, 9, 6, 2 }; 12 | printArr(v, ARR_LEN); 13 | qsort(v, 0, ARR_LEN-1); 14 | printArr(v, ARR_LEN); 15 | return 0; 16 | } 17 | 18 | void qsort(int v[], int left, int right) 19 | { 20 | int i, last; 21 | void swap(int v[], int i, int j); 22 | 23 | if (left >= right) 24 | return; 25 | swap(v, left, (left + right) / 2); 26 | last = left; 27 | for (i = left+1; i <= right; i++) 28 | if (v[i] < v[left]) 29 | swap(v, ++last, i); 30 | swap(v, left, last); 31 | qsort(v, left, last-1); 32 | qsort(v, last+1, right); 33 | } 34 | 35 | void swap(int v[], int i, int j) 36 | { 37 | int temp; 38 | 39 | temp = v[i]; 40 | v[i] = v[j]; 41 | v[j] = temp; 42 | } 43 | 44 | void printArr(int v[], int len) 45 | { 46 | int i; 47 | for (i = 0; i < len; i++) 48 | printf("%d ", v[i]); 49 | printf("\n"); 50 | } 51 | 52 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/9.itoa-recursive.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void itoa(int n, char s[]); 5 | 6 | int main() 7 | { 8 | char s[1024]; 9 | int n = INT_MAX; 10 | itoa(n, s); 11 | printf("s: %s, n: %d\n", s, n); 12 | 13 | n = -2147483647; 14 | itoa(n, s); 15 | printf("s: %s, n: %d\n", s, n); 16 | 17 | n = -INT_MAX; 18 | itoa(n, s); 19 | printf("s: %s, n: %d\n", s, n); 20 | 21 | n = -0; 22 | itoa(n, s); 23 | printf("s: %s, n: %d\n", s, n); 24 | 25 | n = 0; 26 | itoa(n, s); 27 | printf("s: %s, n: %d\n", s, n); 28 | 29 | return 0; 30 | } 31 | 32 | void itoa(int n, char s[]) 33 | { 34 | if (n < 0) { 35 | s[0] = '-'; 36 | n = -n; 37 | } 38 | if (n / 10) 39 | itoa(n / 10, s); 40 | 41 | int digits = 0; 42 | int t = n; 43 | while (t = t / 10) 44 | digits++; 45 | if (s[0] == '-') 46 | digits++; 47 | 48 | s[digits++] = n % 10 + '0'; 49 | s[digits] = '\0'; 50 | } 51 | 52 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/atof.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | double atof(char s[]) 4 | { 5 | double val, power; 6 | int i, sign; 7 | 8 | for (i = 0; isspace(s[i]); i++) 9 | ; 10 | 11 | sign = (s[i] == '-') ? -1 : 1; 12 | if (s[i] == '+' || s[i] == '-') 13 | i++; 14 | 15 | for (val = 0.0; isdigit(s[i]); i++) 16 | val = 10.0 * val + (s[i] - '0'); 17 | 18 | if (s[i] == '.') 19 | i++; 20 | 21 | for (power = 1.0; isdigit(s[i]); i++) { 22 | val = 10.0 * val + (s[i] - '0'); 23 | power *= 10.0; 24 | } 25 | 26 | int eSign = 1; 27 | if (s[i] == 'e' || s[i] == 'E') { 28 | if (s[++i] == '-') { 29 | eSign = -1; 30 | i++; 31 | } 32 | } 33 | 34 | double ePower = 1.0; 35 | if (isdigit(s[i])) { 36 | int eCount = s[i] - '0'; 37 | while (eCount-- > 0) 38 | ePower *= 10.0; 39 | } 40 | 41 | double result = sign * val / power; 42 | 43 | if (eSign > 0) 44 | result *= ePower; 45 | else 46 | result /= ePower; 47 | 48 | return result; 49 | } 50 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/calc.h: -------------------------------------------------------------------------------- 1 | #define NUMBER '0' // signal that a number was found 2 | #define FUNC '1' // signal that math function was found 3 | #define VAR '2' // signal that variable was found 4 | 5 | void push(double); 6 | double pop(void); 7 | 8 | int getop(char []); 9 | 10 | int getch(void); 11 | void ungetch(int); 12 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/getch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define BUFSIZE 100 5 | 6 | int buf[BUFSIZE]; 7 | int bufp = 0; 8 | 9 | int value = EOF; 10 | 11 | int getch(void) 12 | { 13 | return (bufp > 0) ? buf[--bufp] : getchar(); 14 | } 15 | 16 | void ungetch(int c) 17 | { 18 | if (bufp >= BUFSIZE) 19 | printf("ungetch: too many characters\n"); 20 | else 21 | buf[bufp++] = c; 22 | } 23 | 24 | void ungetchs(char s[]) 25 | { 26 | int len = strlen(s); 27 | while (len > 0) { 28 | ungetch(s[--len]); 29 | } 30 | } 31 | 32 | int getchOne(void) 33 | { 34 | if (value != EOF) { 35 | int temp = value; 36 | value = EOF; 37 | return temp; 38 | } 39 | else 40 | return getchar(); 41 | } 42 | 43 | void ungetchOne(int c) 44 | { 45 | if (value != EOF) 46 | printf("ungetchOne: cannot ungetch more char\n"); 47 | else 48 | value = c; 49 | } 50 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/getop.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "calc.h" 5 | 6 | int strrindex(char source[], char searchfor[]); 7 | 8 | int getop(char s[]) 9 | { 10 | int i, c; 11 | 12 | while ((s[0] = c = getch()) == ' ' || c == '\t') 13 | ; 14 | 15 | s[1] = '\0'; 16 | 17 | i = 0; 18 | 19 | if (c == '+' || c == '-') { 20 | int op = c; 21 | c = getch(); 22 | if (!isdigit(c) && c != '.') { 23 | ungetch(c); 24 | return op; 25 | } else { 26 | ungetch(c); 27 | } 28 | } else if (isalpha(c)) { 29 | while (isalpha(s[++i] = c = getch())) 30 | ; 31 | ungetch(c); 32 | 33 | if (i == 1) { 34 | s[0] = tolower(s[0]) - 'a'; 35 | s[1] = '\0'; 36 | return VAR; 37 | } 38 | 39 | s[++i] = '\0'; 40 | 41 | int index; 42 | index = strrindex(s, "sin"); 43 | if (index == 0) 44 | return FUNC; 45 | 46 | index = strrindex(s, "exp"); 47 | if (index == 0) 48 | return FUNC; 49 | 50 | index = strrindex(s, "pow"); 51 | if (index == 0) 52 | return FUNC; 53 | 54 | return 0; 55 | } else if (!isdigit(c) && c != '.') { 56 | return c; 57 | } 58 | 59 | i = 0; 60 | 61 | if (isdigit(c)) 62 | while (isdigit(s[++i] = c = getch())) 63 | ; 64 | 65 | if (c == '.') 66 | while (isdigit(s[++i] = c = getch())) 67 | ; 68 | 69 | s[i] = '\0'; 70 | if (c != EOF) 71 | ungetch(c); 72 | return NUMBER; 73 | } 74 | 75 | int strrindex(char s[], char t[]) 76 | { 77 | int i, j, k; 78 | 79 | for (i = strlen(s) - 2; i > 0; i--) { 80 | for (j = i, k = strlen(t) - 1; j > 0 && k > 0 && s[j] == t[k]; j--, k--) 81 | ; 82 | 83 | if (k == 0) 84 | return j; 85 | } 86 | return -1; 87 | } 88 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/mygetline.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | int mygetline(char s[], int lim) 5 | { 6 | int c, i; 7 | i =0; 8 | while (--lim > 0 && (c = getchar()) != EOF && c != '\n') 9 | s[i++] = c; 10 | if (c == '\n') 11 | s[i++] = c; 12 | s[i] = '\0'; 13 | return i; 14 | } 15 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/stack.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAXVAL 100 4 | 5 | int sp = 0; 6 | double val[MAXVAL]; 7 | 8 | void push(double f) 9 | { 10 | if (sp < MAXVAL) 11 | val[sp++] = f; 12 | else 13 | printf("error: stack full, can't push %g\n", f); 14 | } 15 | 16 | double pop(void) 17 | { 18 | if (sp > 0) 19 | return val[--sp]; 20 | else { 21 | printf("error: stack empty\n"); 22 | return 0.0; 23 | } 24 | } 25 | 26 | void top(void) 27 | { 28 | if (sp > 0) 29 | printf("stack top: %g\n", val[sp-1]); 30 | else 31 | printf("stack empty\n"); 32 | } 33 | 34 | void duplicate(void) 35 | { 36 | if (sp > MAXVAL -1) 37 | printf("error: stack full, can't duplicate\n"); 38 | else { 39 | double element = pop(); 40 | push(element); 41 | push(element); 42 | } 43 | } 44 | 45 | void swap(void) 46 | { 47 | if (sp < 2) 48 | printf("error: stack size < 2, can't swap\n"); 49 | else { 50 | double e1 = pop(); 51 | double e2 = pop(); 52 | push(e1); 53 | push(e2); 54 | } 55 | } 56 | 57 | void empty(void) 58 | { 59 | sp = 0; 60 | } 61 | -------------------------------------------------------------------------------- /chapter-4-functions-and-program-structure/sysv.h: -------------------------------------------------------------------------------- 1 | #define OS "sysv" 2 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/1.pointer.c: -------------------------------------------------------------------------------- 1 | int main() 2 | { 3 | int x = 1, y = 2, z[10]; 4 | int *ip; 5 | 6 | ip = &x; 7 | y = *ip; 8 | *ip = 0; 9 | ip = &z[0]; 10 | 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/10.strcpy-pointer-v1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | void mystrcpy(char*, char*); 6 | 7 | char t[] = "Hello, World!"; 8 | char s[100]; 9 | mystrcpy(s, t); 10 | printf("%s\n", s); 11 | 12 | return 0; 13 | } 14 | 15 | void mystrcpy(char *s, char *t) 16 | { 17 | while ((*s = *t) != '\0') { 18 | s++; 19 | t++; 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/11.strcpy-pointer-v2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | void mystrcpy(char*, char*); 6 | 7 | char t[] = "Hello, World!"; 8 | char s[100]; 9 | mystrcpy(s, t); 10 | printf("%s\n", s); 11 | 12 | return 0; 13 | } 14 | 15 | void mystrcpy(char *s, char *t) 16 | { 17 | while ((*s++ = *t++) != '\0') 18 | ; 19 | } 20 | 21 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/12.strcpy-pointer-v3.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | void mystrcpy(char*, char*); 6 | 7 | char t[] = "Hello, World!"; 8 | char s[100]; 9 | mystrcpy(s, t); 10 | printf("%s\n", s); 11 | 12 | return 0; 13 | } 14 | 15 | void mystrcpy(char *s, char *t) 16 | { 17 | while (*s++ = *t++) 18 | ; 19 | } 20 | 21 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/13.strcmp-array-subscript.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int mystrcmp(char*, char*); 6 | 7 | char *s = "Hello"; 8 | char *t = "Hello"; 9 | int diff = mystrcmp(s, t); 10 | printf("%d\n", diff); 11 | 12 | return 0; 13 | } 14 | 15 | int mystrcmp(char *s, char *t) 16 | { 17 | int i; 18 | 19 | for (i = 0; s[i] == t[i]; i++) 20 | if (s[i] == '\0') 21 | return 0; 22 | return s[i] - t[i]; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/14.strcmp-pointer.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int mystrcmp(char*, char*); 6 | 7 | char *s = "Hello"; 8 | char *t = "Hello"; 9 | int diff = mystrcmp(s, t); 10 | printf("%d\n", diff); 11 | 12 | return 0; 13 | } 14 | 15 | int mystrcmp(char *s, char *t) 16 | { 17 | for (; *s == *t; s++, t++) 18 | if (*s == '\0') 19 | return 0; 20 | return *s - *t; 21 | } 22 | 23 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/15.strcat-pointer.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | void mystrcat(char*, char*); 6 | 7 | char s[100] = "Hello"; 8 | char *t = ", World!"; 9 | mystrcat(s, t); 10 | printf("%s\n", s); 11 | 12 | return 0; 13 | } 14 | 15 | void mystrcat(char *s, char *t) 16 | { 17 | while (*s) 18 | s++; 19 | 20 | while ((*s++ = *t++)) 21 | ; 22 | } 23 | 24 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/16.strend.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int strend(char*, char*); 6 | 7 | char *s = "qweasdzxc123Hello"; 8 | char *t = "Hello"; 9 | int end = strend(s, t); 10 | printf("%d\n", end); 11 | 12 | return 0; 13 | } 14 | 15 | int strend(char *s, char *t) 16 | { 17 | char *sStart = s; 18 | char *tStart = t; 19 | 20 | while (*s) 21 | s++; 22 | 23 | while (*t) 24 | t++; 25 | 26 | while ((*s-- == *t--) && (t != tStart) & (s != sStart)) 27 | ; 28 | 29 | if (t == tStart) 30 | return 1; 31 | else 32 | return 0; 33 | } 34 | 35 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/17.strncpy.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | char *mystrncpy(char*, char *, int); 7 | 8 | char s[100]; 9 | char *ct = "hello, world!"; 10 | char *t = mystrncpy(s, ct, 5); 11 | printf("%s\n", s); 12 | printf("%s\n", t); 13 | 14 | t = strncpy(s, ct, 8); 15 | printf("%s\n", t); 16 | 17 | return 0; 18 | } 19 | 20 | char *mystrncpy(char *s, char *ct, int n) 21 | { 22 | char *start = s; 23 | for (; n > 0 && *ct != '\0'; n--) { 24 | *s++ = *ct++; 25 | } 26 | 27 | while (n-- > 0) 28 | *s++ = '\0'; 29 | 30 | return start; 31 | } 32 | 33 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/18.strncat.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | char *mystrncat(char*, char *, int); 7 | 8 | char s[100] = "Hello, "; 9 | char *ct = "world!"; 10 | char *t = mystrncat(s, ct, 5); 11 | printf("%s\n", s); 12 | printf("%s\n", t); 13 | 14 | t = strncat(s, ct, 8); 15 | printf("%s\n", t); 16 | 17 | return 0; 18 | } 19 | 20 | char *mystrncat(char *s, char *ct, int n) 21 | { 22 | char *ts = s; 23 | while (*++ts) 24 | ; 25 | 26 | for (; n > 0 && ct != '\0'; n--) 27 | *ts++ = *ct++; 28 | 29 | *ts = '\0'; 30 | 31 | return s; 32 | } 33 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/19.strncmp.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int mystrncmp(char *, char *, int); 7 | 8 | char *s = "Hellp"; 9 | char *t = "Hello"; 10 | int diff = mystrncmp(s, t, 5); 11 | printf("%d\n", diff); 12 | 13 | diff = strncmp(s, t, 5); 14 | printf("%d\n", diff); 15 | 16 | return 0; 17 | } 18 | 19 | int mystrncmp(char *cs, char *ct, int n) 20 | { 21 | for (; *cs == *ct && n > 0; cs++, ct++) 22 | if (*cs == '\0') 23 | return 0; 24 | 25 | if (n == 0) 26 | return 0; 27 | 28 | return *cs - *ct; 29 | } 30 | 31 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/2.swap.c: -------------------------------------------------------------------------------- 1 | int main() 2 | { 3 | } 4 | 5 | void swap(int *px, int *py) 6 | { 7 | int temp; 8 | 9 | temp = *px; 10 | *px = *py; 11 | *py = temp; 12 | } 13 | 14 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/20.getline-pointer.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int mygetline(char *, int); 6 | char s[100]; 7 | int len = mygetline(s, 100); 8 | printf("%d %s\n", len, s); 9 | 10 | return 0; 11 | } 12 | 13 | int mygetline(char *s, int lim) 14 | { 15 | int c; 16 | char *t = s; 17 | while (--lim > 0 && (c = getchar()) != EOF && c != '\n') 18 | *s++ = c; 19 | 20 | if (c == '\n') 21 | *s++ = c; 22 | 23 | *s = '\0'; 24 | return s - t - 1; 25 | } 26 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/21.atoi.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | printf("%d\n", atoi("123")); 7 | printf("%d\n", atoi("+1")); 8 | printf("%d\n", atoi("-0")); 9 | printf("%d\n", atoi("-123")); 10 | printf("%d\n", atoi("asd345")); 11 | printf("%d\n", atoi("789asd345")); 12 | 13 | return 0; 14 | } 15 | 16 | int atoi(char *s) 17 | { 18 | int sign, n; 19 | 20 | while (isspace(*s)) 21 | s++; 22 | 23 | sign = (*s == '-') ? -1 : 1; 24 | 25 | if (*s == '+' || *s == '-') 26 | s++; 27 | 28 | n = 0; 29 | while (isdigit(*s)) 30 | n = 10 * n + (*s++ - '0'); 31 | 32 | return sign * n; 33 | } 34 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/22.itoa.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() 7 | { 8 | void itoa(int, char*); 9 | 10 | int n = 0; 11 | char s[10]; 12 | itoa(n, s); 13 | printf("%d to %s\n", n, s); 14 | 15 | n = -0; 16 | itoa(n, s); 17 | printf("%d to %s\n", n, s); 18 | 19 | n = 1234; 20 | itoa(n, s); 21 | printf("%d to %s\n", n, s); 22 | 23 | n = INT_MIN; 24 | itoa(n, s); 25 | printf("%d to %s\n", n, s); 26 | 27 | n = INT_MAX; 28 | itoa(n, s); 29 | printf("%d to %s\n", n, s); 30 | 31 | return 0; 32 | } 33 | 34 | void itoa(int n, char *s) 35 | { 36 | void reverse(char*); 37 | 38 | char *p = s; 39 | int sign = n; 40 | 41 | do { 42 | *s++ = abs(n % 10) + '0'; 43 | } while (n /= 10); 44 | 45 | if (sign < 0) 46 | *s++ = '-'; 47 | 48 | 49 | *s = '\0'; 50 | reverse(p); 51 | } 52 | 53 | void reverse(char *s) 54 | { 55 | char *t = s + strlen(s) - 1; 56 | char c; 57 | 58 | while (s < t) { 59 | c = *s; 60 | *s = *t; 61 | *t = c; 62 | s++; 63 | t--; 64 | } 65 | } 66 | 67 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/23.pointer-arrays.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAXLINES 50000 6 | 7 | char *lineptr[MAXLINES]; 8 | 9 | int readlines(char *lineptr[], int nlines); 10 | void writelines(char *lineptr[], int nlines); 11 | 12 | void qsort(char *lineptr[], int left, int right); 13 | 14 | int main() 15 | { 16 | int nlines; 17 | 18 | if ((nlines = readlines(lineptr, MAXLINES)) >= 0) { 19 | qsort(lineptr, 0, nlines-1); 20 | //writelines(lineptr, nlines); 21 | return 0; 22 | } else { 23 | printf("error: input too big to sort\n"); 24 | return 1; 25 | } 26 | 27 | return 0; 28 | } 29 | 30 | #define MAXLEN 1000 31 | 32 | int mygetline(char *, int); 33 | char *alloc(int); 34 | 35 | int readlines(char *lineptr[], int maxlines) 36 | { 37 | clock_t start, finish; 38 | start = clock(); 39 | 40 | int len, nlines; 41 | char *p, line[MAXLEN]; 42 | nlines = 0; 43 | while ((len = mygetline(line, MAXLEN)) > 0) 44 | if (nlines >= maxlines || (p = alloc(len)) == NULL) 45 | return -1; 46 | else { 47 | line[len-1] = '\0'; 48 | strcpy(p, line); 49 | lineptr[nlines++] = p; 50 | } 51 | 52 | finish = clock(); 53 | printf("alloc: %f\n", ((double)(finish - start)) / CLOCKS_PER_SEC); 54 | return nlines; 55 | } 56 | 57 | void writelines(char *lineptr[], int nlines) 58 | { 59 | while (nlines-- > 0) 60 | printf("%s\n", *lineptr++); 61 | } 62 | 63 | int mygetline(char *s, int lim) 64 | { 65 | int c; 66 | char *t = s; 67 | while (--lim > 0 && (c = getchar()) != EOF && c != '\n') 68 | *t++ = c; 69 | 70 | if (c == '\n') 71 | *t++ = c; 72 | 73 | *t = '\0'; 74 | return t - s; 75 | } 76 | 77 | void qsort(char *v[], int left, int right) 78 | { 79 | int i, last; 80 | void swap(char *v[], int i, int j); 81 | if (left >= right) 82 | return; 83 | swap(v, left, (left + right)/2); 84 | last = left; 85 | for (i = left+1; i <= right; i++) 86 | if (strcmp(v[i], v[left]) < 0) 87 | swap(v, ++last, i); 88 | swap(v, left, last); 89 | qsort(v, left, last-1); 90 | qsort(v, last+1, right); 91 | } 92 | 93 | void swap(char *v[], int i, int j) 94 | { 95 | char *temp; 96 | 97 | temp = v[i]; 98 | v[i] = v[j]; 99 | v[j] = temp; 100 | } 101 | 102 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/24.pointer-arrays-without-alloc.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAXLINES 50000 6 | 7 | #define ARR_SIZE 1000000 8 | 9 | char strstore[ARR_SIZE]; 10 | 11 | char *lineptr[MAXLINES]; 12 | 13 | int readlines(char *lineptr[], int nlines); 14 | void writelines(char *lineptr[], int nlines); 15 | 16 | void qsort(char *lineptr[], int left, int right); 17 | 18 | int main() 19 | { 20 | int nlines; 21 | 22 | if ((nlines = readlines(lineptr, MAXLINES)) >= 0) { 23 | qsort(lineptr, 0, nlines-1); 24 | //writelines(lineptr, nlines); 25 | return 0; 26 | } else { 27 | printf("error: input too big to sort\n"); 28 | return 1; 29 | } 30 | 31 | return 0; 32 | } 33 | 34 | #define MAXLEN 1000 35 | 36 | int mygetline(char *, int); 37 | char *alloc(int); 38 | 39 | int readlines(char *lineptr[], int maxlines) 40 | { 41 | clock_t start, finish; 42 | start = clock(); 43 | 44 | int len, nlines; 45 | int offset = 0; 46 | char *p, line[MAXLEN]; 47 | nlines = 0; 48 | while ((len = mygetline(line, MAXLEN)) > 0) 49 | if (nlines >= maxlines || (p = &strstore[offset]) == NULL) 50 | return -1; 51 | else { 52 | line[len-1] = '\0'; 53 | strcpy(p, line); 54 | offset += len; 55 | lineptr[nlines++] = p; 56 | } 57 | 58 | finish = clock(); 59 | printf("without alloc: %f\n", ((double)(finish - start)) / CLOCKS_PER_SEC); 60 | return nlines; 61 | } 62 | 63 | void writelines(char *lineptr[], int nlines) 64 | { 65 | while (nlines-- > 0) 66 | printf("%s\n", *lineptr++); 67 | } 68 | 69 | int mygetline(char *s, int lim) 70 | { 71 | int c; 72 | char *t = s; 73 | while (--lim > 0 && (c = getchar()) != EOF && c != '\n') 74 | *t++ = c; 75 | 76 | if (c == '\n') 77 | *t++ = c; 78 | 79 | *t = '\0'; 80 | return t - s; 81 | } 82 | 83 | void qsort(char *v[], int left, int right) 84 | { 85 | int i, last; 86 | void swap(char *v[], int i, int j); 87 | if (left >= right) 88 | return; 89 | swap(v, left, (left + right)/2); 90 | last = left; 91 | for (i = left+1; i <= right; i++) 92 | if (strcmp(v[i], v[left]) < 0) 93 | swap(v, ++last, i); 94 | swap(v, left, last); 95 | qsort(v, left, last-1); 96 | qsort(v, last+1, right); 97 | } 98 | 99 | void swap(char *v[], int i, int j) 100 | { 101 | char *temp; 102 | 103 | temp = v[i]; 104 | v[i] = v[j]; 105 | v[j] = temp; 106 | } 107 | 108 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/25.year-month-day.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | static char daytab[2][13] = { 4 | {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, 5 | {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} 6 | }; 7 | 8 | int main() 9 | { 10 | int day_of_year(int, int, int); 11 | void month_day(int, int, int*, int*); 12 | 13 | int day = day_of_year(2018, 8, 19); 14 | printf("%d\n", day); 15 | 16 | day = day_of_year(2018, 13, 19); 17 | printf("%d\n", day); 18 | 19 | day = day_of_year(2018, 12, 39); 20 | printf("%d\n", day); 21 | 22 | day = day_of_year(2018, 12, 0); 23 | printf("%d\n", day); 24 | 25 | int month; 26 | month_day(2018, 231, &month, &day); 27 | printf("%d, %d\n", month, day); 28 | 29 | month_day(2018, -1, &month, &day); 30 | printf("%d, %d\n", month, day); 31 | 32 | month_day(2018, 1234, &month, &day); 33 | printf("%d, %d\n", month, day); 34 | 35 | month_day(2018, 365, &month, &day); 36 | printf("%d, %d\n", month, day); 37 | 38 | month_day(2018, 366, &month, &day); 39 | printf("%d, %d\n", month, day); 40 | 41 | month_day(2016, 366, &month, &day); 42 | printf("%d, %d\n", month, day); 43 | 44 | return 0; 45 | } 46 | 47 | int day_of_year(int year, int month, int day) 48 | { 49 | int i, leap; 50 | if (month < 1 || month > 12) { 51 | printf("error: invalid month: %d\n", month); 52 | return -1; 53 | } 54 | 55 | leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0; 56 | 57 | if (day < 1 || day > daytab[leap][month]) { 58 | printf("error: invalid day: %d\n", day); 59 | return -1; 60 | } 61 | 62 | for (i = 1; i < month; i++) 63 | day += daytab[leap][i]; 64 | return day; 65 | } 66 | 67 | void month_day(int year, int yearday, int *pmonth, int *pday) 68 | { 69 | int i, leap; 70 | leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0; 71 | if (yearday < 1) { 72 | printf("error: invalid yearday: %d\n", yearday); 73 | return; 74 | } else if (leap == 1 && yearday > 366) { 75 | printf("error: invalid yearday: %d\n", yearday); 76 | return; 77 | } else if (leap == 0 && yearday > 365) { 78 | printf("error: invalid yearday: %d\n", yearday); 79 | return; 80 | } 81 | 82 | for (i = 1; yearday > daytab[leap][i]; i++) 83 | yearday -= daytab[leap][i]; 84 | *pmonth = i; 85 | *pday = yearday; 86 | } 87 | 88 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/26.pointer-array-init.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | char *month_name(int); 6 | 7 | char *n = month_name(9); 8 | printf("%s\n", n); 9 | 10 | return 0; 11 | } 12 | 13 | char *month_name(int n) 14 | { 15 | static char *name[] = { 16 | "Illegal month", 17 | "January", "February", "March", 18 | "Aprial", "May", "June", 19 | "July", "August", "September", 20 | "October", "November", "December" 21 | }; 22 | 23 | return (n < 1 || n > 12) ? name[0] : name[n]; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/27.year-month-day-pointer.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | char a[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 4 | char b[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 5 | 6 | static char *daytab[2] = {a, b}; 7 | /* 8 | static char *daytab[2] = { 9 | {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, 10 | {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} 11 | }; 12 | */ 13 | 14 | char *name[] = {"Jan", "Feb"}; 15 | char n0[][10] = { {"Jan"}, {"Feb"} }; 16 | char n1[][10] = { "Jan", "Feb" }; 17 | //char *n2[] = { {"Jan"}, {"Feb"} }; 18 | 19 | int main() 20 | { 21 | int day_of_year(int, int, int); 22 | void month_day(int, int, int*, int*); 23 | 24 | int day = day_of_year(2018, 8, 19); 25 | printf("%d\n", day); 26 | 27 | day = day_of_year(2018, 13, 19); 28 | printf("%d\n", day); 29 | 30 | day = day_of_year(2018, 12, 39); 31 | printf("%d\n", day); 32 | 33 | day = day_of_year(2018, 12, 0); 34 | printf("%d\n", day); 35 | 36 | int month; 37 | month_day(2018, 231, &month, &day); 38 | printf("%d, %d\n", month, day); 39 | 40 | month_day(2018, -1, &month, &day); 41 | printf("%d, %d\n", month, day); 42 | 43 | month_day(2018, 1234, &month, &day); 44 | printf("%d, %d\n", month, day); 45 | 46 | month_day(2018, 365, &month, &day); 47 | printf("%d, %d\n", month, day); 48 | 49 | month_day(2018, 366, &month, &day); 50 | printf("%d, %d\n", month, day); 51 | 52 | month_day(2016, 366, &month, &day); 53 | printf("%d, %d\n", month, day); 54 | 55 | return 0; 56 | } 57 | 58 | int day_of_year(int year, int month, int day) 59 | { 60 | int i, leap; 61 | if (month < 1 || month > 12) { 62 | printf("error: invalid month: %d\n", month); 63 | return -1; 64 | } 65 | 66 | leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0; 67 | 68 | if (day < 1 || day > daytab[leap][month]) { 69 | printf("error: invalid day: %d\n", day); 70 | return -1; 71 | } 72 | 73 | char *p = daytab[leap] + 1; 74 | 75 | for (i = 1; i < month; i++) 76 | day += *p++; 77 | return day; 78 | } 79 | 80 | void month_day(int year, int yearday, int *pmonth, int *pday) 81 | { 82 | int i, leap; 83 | leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0; 84 | if (yearday < 1) { 85 | printf("error: invalid yearday: %d\n", yearday); 86 | return; 87 | } else if (leap == 1 && yearday > 366) { 88 | printf("error: invalid yearday: %d\n", yearday); 89 | return; 90 | } else if (leap == 0 && yearday > 365) { 91 | printf("error: invalid yearday: %d\n", yearday); 92 | return; 93 | } 94 | 95 | char *p = daytab[leap] + 1; 96 | 97 | for (i = 1; yearday > *p; i++) 98 | yearday -= *p++; 99 | *pmonth = i; 100 | *pday = yearday; 101 | } 102 | 103 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/28.echo-v1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main(int argc, char *argv[]) 4 | { 5 | int i; 6 | 7 | for (i = 1; i < argc; i++) 8 | printf("%s%s", argv[i], (i < argc-1) ? " " : ""); 9 | printf("\n"); 10 | 11 | return 0; 12 | } 13 | 14 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/29.echo-v2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main(int argc, char *argv[]) 4 | { 5 | while (--argc > 0) 6 | printf("%s%s", *++argv, (argc > 1) ? " " : ""); 7 | //printf((argc > 1) ? "%s " : "%s", *++argv); 8 | printf("\n"); 9 | 10 | return 0; 11 | } 12 | 13 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/3.getint.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define SIZE 10 5 | 6 | int getch(void); 7 | void ungetch(int); 8 | 9 | // compile with getch.c 10 | int main() 11 | { 12 | int n, array[SIZE], getint(int *); 13 | 14 | for (n = 0; n < SIZE; n++) 15 | array[n] = 0; 16 | 17 | for (n = 0; n < SIZE && getint(&array[n]) != EOF; n++) 18 | ; 19 | 20 | for (n = 0; n < SIZE; n++) 21 | printf("%d ", array[n]); 22 | 23 | printf("\n"); 24 | return 0; 25 | } 26 | 27 | int getint(int *pn) 28 | { 29 | int c, sign; 30 | 31 | while (isspace(c = getch())) 32 | ; 33 | 34 | if (!isdigit(c) && c != EOF && c != '+' && c != '-') { 35 | ungetch(c); 36 | return 0; 37 | } 38 | sign = (c == '-') ? -1 : 1; 39 | if (c == '+' || c == '-') { 40 | c = getch(); 41 | if (!isdigit(c)) { 42 | ungetch(sign == 1 ? '+' : '-'); 43 | return 0; 44 | } 45 | } 46 | for (*pn = 0; isdigit(c); c = getch()) 47 | *pn = 10 * *pn + (c - '0'); 48 | *pn *= sign; 49 | if (c != EOF) 50 | ungetch(c); 51 | return c; 52 | } 53 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/30.find.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define MAXLINE 1000 4 | 5 | int mygetline(char *line, int max); 6 | 7 | main(int argc, char *argv[]) 8 | { 9 | char line[MAXLINE]; 10 | int found = 0; 11 | 12 | if (argc != 2) 13 | printf("Usage: find pattern\n"); 14 | else 15 | while (mygetline(line, MAXLINE) > 0) 16 | if (strstr(line, argv[1]) != NULL) { 17 | printf("%s", line); 18 | found++; 19 | } 20 | return found; 21 | } 22 | 23 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/31.find.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAXLINE 1000 5 | 6 | int mygetline(char *line, int max); 7 | 8 | main(int argc, char *argv[]) 9 | { 10 | char line[MAXLINE]; 11 | long lineno = 0; 12 | int c, except = 0, number = 0, found = 0; 13 | 14 | while (--argc > 0 && (*++argv)[0] == '-') 15 | while (c = *++argv[0]) 16 | switch(c) { 17 | case 'x': 18 | except = 1; 19 | break; 20 | case 'n': 21 | number = 1; 22 | break; 23 | default: 24 | printf("find: illegal option %c\n", c); 25 | argc = 0; 26 | found = -1; 27 | break; 28 | } 29 | if (argc != 1) 30 | printf("Usage: find -x -n pattern\n"); 31 | else 32 | while (mygetline(line, MAXLINE) > 0) { 33 | lineno++; 34 | if ((strstr(line, *argv) != NULL) != except) { 35 | if (number) 36 | printf("%ld:", lineno); 37 | printf("%s", line); 38 | found++; 39 | } 40 | } 41 | return found; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/32.expr.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAXOP 100 5 | #define NUMBER '0' 6 | 7 | int getop(char [], int, char **); 8 | void push(double); 9 | double pop(void); 10 | 11 | main(int argc, char **argv) 12 | { 13 | int type; 14 | double op2; 15 | char s[MAXOP]; 16 | 17 | if (argc == 1) { 18 | printf("Usage: expr 1 1 +\n"); 19 | return 1; 20 | } 21 | 22 | while ((type = getop(s, --argc, ++argv)) != EOF) { 23 | switch (type) { 24 | case NUMBER: 25 | push(atof(s)); 26 | break; 27 | case '+': 28 | push(pop() + pop()); 29 | break; 30 | case '*': 31 | push(pop() * pop()); 32 | break; 33 | case '-': 34 | op2 = pop(); 35 | push(pop() - op2); 36 | break; 37 | case '/': 38 | op2 = pop(); 39 | if (op2 != 0.0) 40 | push(pop() / op2); 41 | else 42 | printf("error: zero divisor\n"); 43 | break; 44 | default: 45 | printf("error: unknown command %s\n", s); 46 | break; 47 | } 48 | } 49 | 50 | printf("Result: %g\n", pop()); 51 | 52 | return 0; 53 | } 54 | 55 | 56 | #define MAXVAL 100 57 | 58 | int sp = 0; 59 | double val[MAXVAL]; 60 | 61 | void push(double f) 62 | { 63 | if (sp < MAXVAL) 64 | val[sp++] = f; 65 | else 66 | printf("error: stack full, can't push %g\n", f); 67 | } 68 | 69 | double pop(void) 70 | { 71 | if (sp > 0) 72 | return val[--sp]; 73 | else { 74 | printf("error: stack empty\n"); 75 | return 0.0; 76 | } 77 | } 78 | 79 | int getop(char *s, int argc, char **argv) 80 | { 81 | if (argc == 0) 82 | return EOF; 83 | 84 | char *param = *argv; 85 | 86 | int c; 87 | 88 | while ((*s = c = *param++) == ' ' || c == '\t') 89 | ; 90 | 91 | *++s = '\0'; 92 | 93 | if (!isdigit(c) && c != '.') 94 | return c; 95 | 96 | if (isdigit(c)) 97 | while (isdigit(*s++ = c = *param++)) 98 | ; 99 | 100 | 101 | if (c == '.') 102 | while (isdigit(*s++ = c = *param++)) 103 | ; 104 | 105 | *s = '\0'; 106 | 107 | return NUMBER; 108 | } 109 | 110 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/33.detab.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main(int argc, char *argv[]) 4 | { 5 | int c, n, i; 6 | int cur; 7 | 8 | if (argc == 1) 9 | n = 8; 10 | else if (argc == 2) 11 | n = atoi(*++argv); 12 | else { 13 | printf("Usage: detab (8)(tab stop)\n"); 14 | return 1; 15 | } 16 | 17 | cur = 0; 18 | 19 | while ((c = getchar()) != EOF) { 20 | if (c == '\t') { 21 | for (i = n - cur; i > 0; --i) 22 | putchar(' '); 23 | 24 | cur = 0; 25 | } else { 26 | putchar(c); 27 | ++cur; 28 | if (cur >= n || c == '\n') 29 | cur = 0; 30 | } 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/34.entab.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAXLINE 1000 4 | 5 | int myGetline(char line[], int maxline); 6 | 7 | main(int argc, char *argv[]) 8 | { 9 | int c, len; 10 | int i; 11 | char line[MAXLINE]; 12 | int tabstop; 13 | int spaceCount; 14 | 15 | if (argc == 1) 16 | tabstop = 8; 17 | else if (argc == 2) 18 | tabstop = atoi(*++argv); 19 | else { 20 | printf("Usage entab (8)(tabstop)\n"); 21 | return 1; 22 | } 23 | 24 | while ((len = myGetline(line, MAXLINE)) > 0) { 25 | spaceCount = 0; 26 | 27 | for (i = 0; i < len; ++i) { 28 | if (line[i] == ' ') 29 | spaceCount++; 30 | else 31 | spaceCount = 0; 32 | 33 | if (spaceCount == tabstop) { 34 | } 35 | } 36 | printf("%s", line); 37 | } 38 | } 39 | 40 | int myGetline(char s[], int lim) 41 | { 42 | int c, i; 43 | 44 | for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) 45 | s[i] = c; 46 | if (c == '\n') { 47 | s[i] = c; 48 | ++i; 49 | } 50 | s[i] = '\0'; 51 | return i; 52 | } 53 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/35.detab-arg.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main(int argc, char *argv[]) 4 | { 5 | } 6 | 7 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/36.entab-arg.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main(int argc, char *argv[]) 4 | { 5 | } 6 | 7 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/37.tail.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAXLINES 50000 5 | #define MAXLEN 10000 6 | 7 | int mygetline(char *line, int max); 8 | 9 | char *alloc(int); 10 | void afree(char*); 11 | 12 | main(int argc, char *argv[]) 13 | { 14 | int n; 15 | 16 | if (argc == 1) 17 | n = 10; 18 | else if (argc == 2 && (*++argv)[0] == '-') { 19 | n = atoi(*argv + 1); 20 | if (n < 1) 21 | n = 10; 22 | } else { 23 | printf("Usage: tail -n\n"); 24 | return 1; 25 | } 26 | 27 | char line[MAXLEN], *lineptr[MAXLINES]; 28 | int len; 29 | char *p; 30 | int lines = 0; 31 | 32 | while ((len = mygetline(line, MAXLEN)) > 0) { 33 | p = alloc(len + 1); 34 | strcpy(p, line); 35 | lineptr[lines++] = p; 36 | } 37 | 38 | 39 | int i = lines - n; 40 | i = (i >= 0) ? i : 0; 41 | 42 | while (n-- > 0 && i <= lines) { 43 | printf("%s", lineptr[i++]); 44 | } 45 | 46 | return 0; 47 | } 48 | 49 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/38.pointers-to-functions.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAXLINES 5000 5 | char *lineptr[MAXLINES]; 6 | 7 | int readlines(char *lineptr[], int nlines); 8 | void writelines(char *lineptr[], int nlines); 9 | 10 | void qsort(void *lineptr[], int left, int right, 11 | int (*comp)(void *, void *)); 12 | 13 | int numcmp(const char *, const char *); 14 | 15 | // gcc 38.pointers-to-functions.c numcmp.c readlines-writelines.c 6.alloc.c 16 | main(int argc, char *argv[]) 17 | { 18 | int nlines; 19 | int numeric = 0; 20 | 21 | if (argc > 1 && strcmp(argv[1], "-n") == 0) 22 | numeric = 1; 23 | if ((nlines = readlines(lineptr, MAXLINES)) >= 0) { 24 | qsort((void **) lineptr, 0, nlines-1, 25 | (int (*)(void*, void*))(numeric ? numcmp : strcmp)); 26 | writelines(lineptr, nlines); 27 | return 0; 28 | } else { 29 | printf("input too big to sort\n"); 30 | return 1; 31 | } 32 | } 33 | 34 | void qsort(void *v[], int left, int right, 35 | int (*comp)(void *, void *)) 36 | { 37 | int i, last; 38 | void swap(void *v[], int, int); 39 | 40 | if (left >= right) 41 | return; 42 | swap(v, left, (left + right)/2); 43 | last = left; 44 | for (i = left+1; i <= right; i++) 45 | if ((*comp)(v[i], v[left]) < 0) 46 | swap(v, ++last, i); 47 | swap(v, left, last); 48 | qsort(v, left, last-1, comp); 49 | qsort(v, last+1, right, comp); 50 | } 51 | 52 | void swap(void *v[], int i, int j) 53 | { 54 | void *temp; 55 | temp = v[i]; 56 | v[i] = v[j]; 57 | v[j] = temp; 58 | } 59 | 60 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/39.sort-with-r.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAXLINES 5000 5 | char *lineptr[MAXLINES]; 6 | 7 | int readlines(char *lineptr[], int nlines); 8 | void writelines(char *lineptr[], int nlines); 9 | 10 | void qsort(void *lineptr[], int left, int right, 11 | int reverse, int (*comp)(void *, void *)); 12 | 13 | int numcmp(const char *, const char *); 14 | 15 | // gcc 39.sort-with-r.c numcmp.c readlines-writelines.c 6.alloc.c 16 | main(int argc, char *argv[]) 17 | { 18 | char c; 19 | int nlines; 20 | int numeric = 0; 21 | int reverse = 0; 22 | 23 | while (--argc > 0 && (*++argv)[0] == '-') 24 | while (c = *++argv[0]) 25 | switch(c) { 26 | case 'n': 27 | numeric = 1; 28 | break; 29 | case 'r': 30 | reverse = 1; 31 | break; 32 | default: 33 | printf("find illegal option %c\n", c); 34 | return 1; 35 | } 36 | 37 | if (argc != 0) { 38 | printf("Usage: sort -n -r\n"); 39 | return 1; 40 | } 41 | 42 | if ((nlines = readlines(lineptr, MAXLINES)) >= 0) { 43 | qsort((void **) lineptr, 0, nlines-1, reverse, 44 | (int (*)(void*, void*))(numeric ? numcmp : strcmp)); 45 | writelines(lineptr, nlines); 46 | return 0; 47 | } else { 48 | printf("input too big to sort\n"); 49 | return 1; 50 | } 51 | } 52 | 53 | void qsort(void *v[], int left, int right, 54 | int reverse, int (*comp)(void *, void *)) 55 | { 56 | int i, last; 57 | void swap(void *v[], int, int); 58 | 59 | if (left >= right) 60 | return; 61 | swap(v, left, (left + right)/2); 62 | last = left; 63 | for (i = left+1; i <= right; i++) { 64 | if (reverse && ((*comp)(v[i], v[left]) > 0)) 65 | swap(v, ++last, i); 66 | else if (!reverse && ((*comp)(v[i], v[left]) < 0)) 67 | swap(v, ++last, i); 68 | } 69 | swap(v, left, last); 70 | qsort(v, left, last-1, reverse, comp); 71 | qsort(v, last+1, right, reverse, comp); 72 | } 73 | 74 | void swap(void *v[], int i, int j) 75 | { 76 | void *temp; 77 | temp = v[i]; 78 | v[i] = v[j]; 79 | v[j] = temp; 80 | } 81 | 82 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/4.getfloat.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define SIZE 10 5 | 6 | int getch(void); 7 | void ungetch(int); 8 | 9 | // compile with getch.c 10 | int main() 11 | { 12 | int n; 13 | double array[SIZE], getfloat(double *); 14 | 15 | for (n = 0; n < SIZE; n++) 16 | array[n] = 0.0; 17 | 18 | for (n = 0; n < SIZE && getfloat(&array[n]) != EOF; n++) 19 | ; 20 | 21 | for (n = 0; n < SIZE; n++) 22 | printf("%g ", array[n]); 23 | 24 | printf("\n"); 25 | return 0; 26 | } 27 | 28 | double getfloat(double *pn) 29 | { 30 | int c, sign; 31 | double power; 32 | 33 | while (isspace(c = getch())) 34 | ; 35 | 36 | if (!isdigit(c) && c != EOF && c != '+' && c != '-' && c != '.') { 37 | ungetch(c); 38 | return 0.0; 39 | } 40 | sign = (c == '-') ? -1 : 1; 41 | if (c == '+' || c == '-') { 42 | c = getch(); 43 | if (!isdigit(c) && c != '.') { 44 | ungetch(sign == 1 ? '+' : '-'); 45 | return 0.0; 46 | } 47 | } 48 | for (*pn = 0.0; isdigit(c); c = getch()) 49 | *pn = 10.0 * *pn + (c - '0'); 50 | 51 | if (c == '.') { 52 | c = getch(); 53 | } 54 | 55 | for (power = 1.0; isdigit(c); c = getch()) { 56 | *pn = 10.0 * *pn + (c - '0'); 57 | power *= 10.0; 58 | } 59 | 60 | int eSign = 1; 61 | if (c == 'e' || c == 'E') { 62 | c = getch(); 63 | if (c == '-') { 64 | eSign = -1; 65 | c = getch(); 66 | } else if (c == '+') { 67 | c = getch(); 68 | } 69 | } 70 | 71 | double ePower = 1.0; 72 | int eCount = 0; 73 | for (eCount = 0; isdigit(c); c = getch()) 74 | eCount = 10.0 * eCount + (c - '0'); 75 | 76 | while (eCount-- > 0) 77 | ePower *= 10; 78 | 79 | *pn = *pn / power * sign; 80 | 81 | if (eSign > 0) 82 | *pn *= ePower; 83 | else 84 | *pn /= ePower; 85 | 86 | if (c != EOF) 87 | ungetch(c); 88 | return c; 89 | } 90 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/40.sort-with-f.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAXLEN 10000 5 | 6 | #define MAXLINES 5000 7 | char *lineptr[MAXLINES]; 8 | 9 | int readlines(char *lineptr[], int nlines); 10 | void writelines(char *lineptr[], int nlines); 11 | 12 | void qsort(void *lineptr[], int left, int right, 13 | int reverse, int foldcase, int (*comp)(void *, void *)); 14 | 15 | int numcmp(const char *, const char *); 16 | 17 | void strtolower(const char *src, char *dst); 18 | 19 | // gcc 40.sort-with-f.c numcmp.c readlines-writelines.c 6.alloc.c case-convert.c 20 | main(int argc, char *argv[]) 21 | { 22 | char c; 23 | int nlines; 24 | int numeric = 0; 25 | int reverse = 0; 26 | int foldcase = 0; 27 | 28 | while (--argc > 0 && (*++argv)[0] == '-') 29 | while (c = *++argv[0]) 30 | switch(c) { 31 | case 'n': 32 | numeric = 1; 33 | break; 34 | case 'r': 35 | reverse = 1; 36 | break; 37 | case 'f': 38 | foldcase = 1; 39 | break; 40 | default: 41 | printf("find illegal option %c\n", c); 42 | return 1; 43 | } 44 | 45 | if (argc != 0) { 46 | printf("Usage: sort -n -r\n"); 47 | return 1; 48 | } 49 | 50 | if ((nlines = readlines(lineptr, MAXLINES)) >= 0) { 51 | qsort((void **) lineptr, 0, nlines-1, reverse, foldcase, 52 | (int (*)(void*, void*))(numeric ? numcmp : strcmp)); 53 | writelines(lineptr, nlines); 54 | return 0; 55 | } else { 56 | printf("input too big to sort\n"); 57 | return 1; 58 | } 59 | } 60 | 61 | void qsort(void *v[], int left, int right, 62 | int reverse, int foldcase, int (*comp)(void *, void *)) 63 | { 64 | int i, last; 65 | void swap(void *v[], int, int); 66 | char s1[MAXLEN], s2[MAXLEN]; 67 | 68 | if (left >= right) 69 | return; 70 | swap(v, left, (left + right)/2); 71 | last = left; 72 | for (i = left+1; i <= right; i++) { 73 | char *vi; 74 | char *vleft; 75 | 76 | if (foldcase) { 77 | strtolower(v[i], s1); 78 | vi = s1; 79 | strtolower(v[left], s2); 80 | vleft = s2; 81 | } else { 82 | vi = v[i]; 83 | vleft = v[left]; 84 | } 85 | 86 | if (reverse && ((*comp)(vi, vleft) > 0)) 87 | swap(v, ++last, i); 88 | else if (!reverse && ((*comp)(vi, vleft) < 0)) 89 | swap(v, ++last, i); 90 | } 91 | swap(v, left, last); 92 | qsort(v, left, last-1, reverse, foldcase, comp); 93 | qsort(v, last+1, right, reverse, foldcase, comp); 94 | } 95 | 96 | void swap(void *v[], int i, int j) 97 | { 98 | void *temp; 99 | temp = v[i]; 100 | v[i] = v[j]; 101 | v[j] = temp; 102 | } 103 | 104 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/41.sort-with-d.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAXLEN 10000 5 | 6 | #define MAXLINES 5000 7 | char *lineptr[MAXLINES]; 8 | 9 | int readlines(char *lineptr[], int nlines); 10 | void writelines(char *lineptr[], int nlines); 11 | 12 | void swap(void *v[], int, int); 13 | 14 | void qsort(void *lineptr[], int left, int right, 15 | int reverse, int foldcase, int (*comp)(void *, void *)); 16 | 17 | // because qsort is unstable, to test -d 18 | void bubblesort(void *lineptr[], int len, int (*comp)(void*, void*)); 19 | 20 | int numcmp(const char *, const char *); 21 | int dircmp(const char *, const char *); 22 | 23 | void strtolower(const char *src, char *dst); 24 | 25 | // gcc 41.sort-with-d.c numcmp.c readlines-writelines.c 6.alloc.c case-convert.c 26 | main(int argc, char *argv[]) 27 | { 28 | char c; 29 | int nlines; 30 | int numeric = 0; 31 | int reverse = 0; 32 | int foldcase = 0; 33 | int directory = 0; 34 | 35 | while (--argc > 0 && (*++argv)[0] == '-') 36 | while (c = *++argv[0]) 37 | switch(c) { 38 | case 'n': 39 | numeric = 1; 40 | break; 41 | case 'r': 42 | reverse = 1; 43 | break; 44 | case 'f': 45 | foldcase = 1; 46 | break; 47 | case 'd': 48 | directory = 1; 49 | break; 50 | default: 51 | printf("find illegal option %c\n", c); 52 | return 1; 53 | } 54 | 55 | if (argc != 0) { 56 | printf("Usage: sort -n -r\n"); 57 | return 1; 58 | } 59 | 60 | if (numeric && directory) { 61 | printf("Cannot use the -n and -d at the same\n"); 62 | return 1; 63 | } 64 | 65 | if ((nlines = readlines(lineptr, MAXLINES)) >= 0) { 66 | int (*comp)(void*, void*) = (int (*)(void*, void*))(numeric ? numcmp : strcmp); 67 | if (directory) 68 | comp = (int (*)(void*, void*))dircmp; 69 | 70 | if (directory) 71 | bubblesort((void **) lineptr, nlines, comp); 72 | else 73 | qsort((void **) lineptr, 0, nlines-1, reverse, foldcase, comp); 74 | 75 | writelines(lineptr, nlines); 76 | return 0; 77 | } else { 78 | printf("input too big to sort\n"); 79 | return 1; 80 | } 81 | } 82 | 83 | void qsort(void *v[], int left, int right, 84 | int reverse, int foldcase, int (*comp)(void *, void *)) 85 | { 86 | int i, last; 87 | char s1[MAXLEN], s2[MAXLEN]; 88 | 89 | if (left >= right) 90 | return; 91 | swap(v, left, (left + right)/2); 92 | last = left; 93 | for (i = left+1; i <= right; i++) { 94 | char *vi; 95 | char *vleft; 96 | 97 | if (foldcase) { 98 | strtolower(v[i], s1); 99 | vi = s1; 100 | strtolower(v[left], s2); 101 | vleft = s2; 102 | } else { 103 | vi = v[i]; 104 | vleft = v[left]; 105 | } 106 | 107 | if (reverse && ((*comp)(vi, vleft) > 0)) 108 | swap(v, ++last, i); 109 | else if (!reverse && ((*comp)(vi, vleft) < 0)) 110 | swap(v, ++last, i); 111 | } 112 | swap(v, left, last); 113 | qsort(v, left, last-1, reverse, foldcase, comp); 114 | qsort(v, last+1, right, reverse, foldcase, comp); 115 | } 116 | 117 | void bubblesort(void *v[], int len, int (*comp)(void*, void*)) 118 | { 119 | int i, j; 120 | 121 | for (i = 0; i < len; i++) 122 | for (j = 0; j < len; j++) { 123 | if ((*comp)(v[i], v[j]) < 0) 124 | swap(v, i, j); 125 | } 126 | } 127 | 128 | void swap(void *v[], int i, int j) 129 | { 130 | void *temp; 131 | temp = v[i]; 132 | v[i] = v[j]; 133 | v[j] = temp; 134 | } 135 | 136 | int dircmp(const char *p1, const char *p2) 137 | { 138 | char isdircase(const char c); 139 | 140 | const unsigned char *s1 = (const unsigned char *) p1; 141 | const unsigned char *s2 = (const unsigned char *) p2; 142 | unsigned char c1, c2; 143 | 144 | do { 145 | c1 = (unsigned char) *s1++; 146 | c2 = (unsigned char) *s2++; 147 | 148 | // only compare letters, numbers, blanks 149 | if (!isdircase(c1) || !isdircase(c2)) 150 | c2 = c1; 151 | 152 | if (c1 == '\0') 153 | return c1 - c2; 154 | } while (c1 == c2); 155 | 156 | return c1 - c2; 157 | } 158 | 159 | char isdircase(const char c) 160 | { 161 | return isalnum(c) || c == ' '; 162 | } 163 | 164 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/42.dcl.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAXTOKEN 100 6 | 7 | enum { NAME, PARENS, BRACKETS }; 8 | 9 | void dcl(void); 10 | void dirdcl(void); 11 | 12 | int gettoken(void); 13 | int tokentype; // type of last token 14 | char token[MAXTOKEN]; // last token string 15 | char name[MAXTOKEN]; // identifier name 16 | char datatype[MAXTOKEN]; // data type = char, int, etc. 17 | char out[1000]; // output string 18 | 19 | // gcc 42.dcl.c getch.c 20 | main() 21 | { 22 | while (gettoken() != EOF) { // 1st token on line 23 | strcpy(datatype, token); 24 | out[0] = '\0'; 25 | dcl(); 26 | if (tokentype != '\n') 27 | printf("syntax error\n"); 28 | printf("%s: %s %s\n", name, out, datatype); 29 | } 30 | 31 | return 0; 32 | } 33 | 34 | void dcl(void) 35 | { 36 | int ns; 37 | 38 | for (ns = 0; gettoken() == '*';) 39 | ns++; 40 | 41 | dirdcl(); 42 | while (ns-- > 0) 43 | strcat(out, " pointer to"); 44 | } 45 | 46 | void dirdcl(void) 47 | { 48 | int type; 49 | 50 | if (tokentype == '(') { 51 | dcl(); 52 | 53 | if (tokentype != ')') 54 | printf("error: missing )\n"); 55 | } else if (tokentype == NAME) 56 | strcpy(name, token); 57 | else 58 | printf("error: expected name or (dcl)\n"); 59 | 60 | while ((type = gettoken()) == PARENS || type == BRACKETS) 61 | if (type == PARENS) 62 | strcat(out, " function returning"); 63 | else { 64 | strcat(out, " array"); 65 | strcat(out, token); 66 | strcat(out, " of"); 67 | } 68 | } 69 | 70 | int gettoken(void) 71 | { 72 | int c, getch(void); 73 | void ungetch(int); 74 | char *p = token; 75 | 76 | while ((c = getch()) == ' ' || c == '\t') 77 | ; 78 | 79 | if (c == '(') { 80 | if ((c = getch()) == ')') { 81 | strcpy(token, "()"); 82 | return tokentype = PARENS; 83 | } else { 84 | ungetch(c); 85 | return tokentype = '('; 86 | } 87 | } else if (c == '[') { 88 | for (*p++ = c; (*p++ = getch()) != ']'; ) 89 | ; 90 | *p = '\0'; 91 | return tokentype = BRACKETS; 92 | } else if (isalpha(c)) { 93 | for (*p++ = c; isalnum(c = getch()); ) 94 | *p++ = c; 95 | *p = '\0'; 96 | ungetch(c); 97 | return tokentype = NAME; 98 | } else { 99 | return tokentype = c; 100 | } 101 | } 102 | 103 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/43.dcl-error-handle.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAXTOKEN 100 6 | 7 | #define DATATYPE_LEN 6 8 | 9 | enum { NAME, PARENS, BRACKETS }; 10 | 11 | void dcl(void); 12 | void dirdcl(void); 13 | 14 | int isvalid_datatype(const char*); 15 | 16 | int gettoken(void); 17 | int tokentype; // type of last token 18 | char token[MAXTOKEN]; // last token string 19 | char name[MAXTOKEN]; // identifier name 20 | char datatype[MAXTOKEN]; // data type = char, int, etc. 21 | char out[1000]; // output string 22 | 23 | // gcc 43.dcl-error-handle.c getch.c 24 | main() 25 | { 26 | while (gettoken() != EOF) { // 1st token on line 27 | strcpy(datatype, token); 28 | 29 | if (tokentype != NAME) { 30 | printf("%c is not a valid datatype\n", tokentype); 31 | continue; 32 | } else if (!isvalid_datatype(datatype)) { 33 | printf("%s is not a valid datatype\n", datatype); 34 | continue; 35 | } 36 | 37 | out[0] = '\0'; 38 | dcl(); 39 | if (tokentype != '\n') 40 | printf("syntax error\n"); 41 | printf("%s: %s %s\n", name, out, datatype); 42 | } 43 | 44 | return 0; 45 | } 46 | 47 | void dcl(void) 48 | { 49 | int ns; 50 | 51 | for (ns = 0; gettoken() == '*';) 52 | ns++; 53 | 54 | dirdcl(); 55 | while (ns-- > 0) 56 | strcat(out, " pointer to"); 57 | } 58 | 59 | void dirdcl(void) 60 | { 61 | int type; 62 | 63 | if (tokentype == '(') { 64 | dcl(); 65 | 66 | if (tokentype != ')') 67 | printf("error: missing )\n"); 68 | } else if (tokentype == NAME) 69 | strcpy(name, token); 70 | else 71 | printf("error: expected name or (dcl)\n"); 72 | 73 | while ((type = gettoken()) == PARENS || type == BRACKETS) 74 | if (type == PARENS) 75 | strcat(out, " function returning"); 76 | else { 77 | strcat(out, " array"); 78 | strcat(out, token); 79 | strcat(out, " of"); 80 | } 81 | } 82 | 83 | int gettoken(void) 84 | { 85 | int c, getch(void); 86 | void ungetch(int); 87 | char *p = token; 88 | 89 | while ((c = getch()) == ' ' || c == '\t') 90 | ; 91 | 92 | if (c == '(') { 93 | if ((c = getch()) == ')') { 94 | strcpy(token, "()"); 95 | return tokentype = PARENS; 96 | } else { 97 | ungetch(c); 98 | return tokentype = '('; 99 | } 100 | } else if (c == '[') { 101 | for (*p++ = c; (*p++ = getch()) != ']'; ) 102 | ; 103 | *p = '\0'; 104 | return tokentype = BRACKETS; 105 | } else if (isalpha(c)) { 106 | for (*p++ = c; isalnum(c = getch()); ) 107 | *p++ = c; 108 | *p = '\0'; 109 | ungetch(c); 110 | return tokentype = NAME; 111 | } else { 112 | return tokentype = c; 113 | } 114 | } 115 | 116 | int isvalid_datatype(const char* s) 117 | { 118 | char *datatypes[DATATYPE_LEN] = { "char", "short", "int", "long", "float", "double" }; 119 | 120 | int len = 0; 121 | while (len < DATATYPE_LEN) 122 | if (strcmp(s, datatypes[len++]) == 0) 123 | return 1; 124 | 125 | return 0; 126 | } 127 | 128 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/44.undcl.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Exercise 5-19. Modify undcl so that it does not add redundant parentheses to declarations. 3 | * undcl: convert word description to declaration 4 | * 5 | * e.g. 6 | * x * int -> int *x 7 | * argv * * char -> char **argv 8 | * daytab * [] int -> int (*daytab)[] 9 | * daytab [] * int -> int *daytab[] 10 | * comp () * void -> void *comp() 11 | * comp * () void -> void (*comp)() 12 | * x () * [] * () char -> char (*(*x())[])() 13 | * x [] * () * [] char -> char (*(*x[])())[] 14 | */ 15 | 16 | #include 17 | #include 18 | 19 | #define MAXTOKEN 100 20 | 21 | enum { NAME, PARENS, BRACKETS }; 22 | 23 | int gettoken(void); 24 | int tokentype; // type of last token 25 | char token[MAXTOKEN]; // last token string 26 | char out[1000]; // output string 27 | 28 | // gcc 44.undcl.c getch.c 29 | // cat 44.undcl.test | ./a.out 30 | main() 31 | { 32 | int type; 33 | char temp[MAXTOKEN]; 34 | 35 | while (gettoken() != EOF) { 36 | strcpy(out, token); 37 | while ((type = gettoken()) != '\n') { 38 | if (type == PARENS) { 39 | if (out[0] == '*') { 40 | sprintf(temp, "(%s)", out); 41 | strcpy(out, temp); 42 | } 43 | strcat(out, token); 44 | } else if (type == BRACKETS) { 45 | if (out[0] == '*' || strstr(out, "()") != NULL) { 46 | sprintf(temp, "(%s)", out); 47 | strcpy(out, temp); 48 | } 49 | strcat(out, token); 50 | } else if (type == '*') { 51 | sprintf(temp, "*%s", out); 52 | strcpy(out, temp); 53 | } else if (type == NAME) { 54 | sprintf(temp, "%s %s", token, out); 55 | strcpy(out, temp); 56 | } else 57 | printf("invalid input at %s\n", token); 58 | } 59 | 60 | printf("%s\n", out); 61 | } 62 | return 0; 63 | } 64 | 65 | 66 | int gettoken(void) 67 | { 68 | int c, getch(void); 69 | void ungetch(int); 70 | char *p = token; 71 | 72 | while ((c = getch()) == ' ' || c == '\t') 73 | ; 74 | 75 | if (c == '(') { 76 | if ((c = getch()) == ')') { 77 | strcpy(token, "()"); 78 | return tokentype = PARENS; 79 | } else { 80 | ungetch(c); 81 | return tokentype = '('; 82 | } 83 | } else if (c == '[') { 84 | for (*p++ = c; (*p++ = getch()) != ']'; ) 85 | ; 86 | *p = '\0'; 87 | return tokentype = BRACKETS; 88 | } else if (isalpha(c)) { 89 | for (*p++ = c; isalnum(c = getch()); ) 90 | *p++ = c; 91 | *p = '\0'; 92 | ungetch(c); 93 | return tokentype = NAME; 94 | } else { 95 | return tokentype = c; 96 | } 97 | } 98 | 99 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/44.undcl.test: -------------------------------------------------------------------------------- 1 | x * int 2 | argv * * char 3 | daytab * [] int 4 | daytab [] * int 5 | comp () * void 6 | comp * () void 7 | x () * [] * () char 8 | x [] * () * [] char 9 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/5.strlen-pointer.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int strlen(char*); 6 | 7 | char array[100]; 8 | char *ptr = "Hello"; 9 | 10 | int l = strlen("hello, world"); 11 | printf("%d\n", l); 12 | 13 | l = strlen(array); 14 | printf("%d\n", l); 15 | 16 | l = strlen(ptr); 17 | printf("%d\n", l); 18 | } 19 | 20 | int strlen(char *s) 21 | { 22 | int n; 23 | 24 | for (n = 0; *s != '\0'; s++) 25 | n++; 26 | 27 | return n; 28 | } 29 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/6.alloc.c: -------------------------------------------------------------------------------- 1 | #define ALLOCSIZE 1000000 2 | 3 | static char allocbuf[ALLOCSIZE]; 4 | static char *allocp = allocbuf; 5 | 6 | char *alloc(int n) 7 | { 8 | if (allocbuf + ALLOCSIZE - allocp >= n) { 9 | allocp += n; 10 | return allocp - n; 11 | } else 12 | return 0; 13 | } 14 | 15 | void afree(char *p) 16 | { 17 | if (p >= allocbuf && p < allocbuf + ALLOCSIZE) 18 | allocp = p; 19 | } 20 | 21 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/7.alloc.test.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | char *alloc(int); 7 | void afree(char*); 8 | 9 | char *p = alloc(10); 10 | if (NULL == p) 11 | return -1; 12 | 13 | *p++ = 'H'; 14 | *p++ = 'e'; 15 | *p++ = 'l'; 16 | *p++ = 'l'; 17 | *p++ = 'o'; 18 | *p++ = '\0'; 19 | p -= 6; 20 | 21 | printf("%s\n", p); 22 | 23 | afree(p); 24 | 25 | printf("%s\n", p); 26 | 27 | p = alloc(10001); 28 | 29 | if (NULL == p) 30 | printf("overflow!\n"); 31 | 32 | printf("%d\n", NULL); 33 | 34 | return 0; 35 | } 36 | 37 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/8.strlen-address-arithmetic.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int strlen(char*); 6 | 7 | char array[100]; 8 | char *ptr = "Hello"; 9 | 10 | int l = strlen("hello, world"); 11 | printf("%d\n", l); 12 | 13 | l = strlen(array); 14 | printf("%d\n", l); 15 | 16 | l = strlen(ptr); 17 | printf("%d\n", l); 18 | } 19 | 20 | int strlen(char *s) 21 | { 22 | char *p = s; 23 | 24 | while (*p != '\0') 25 | p++; 26 | 27 | return p - s; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/9.strcpy-array-subscript.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | void strcpyArray(char*, char*); 6 | 7 | char t[] = "Hello, World!"; 8 | char s[100]; 9 | strcpyArray(s, t); 10 | printf("%s\n", s); 11 | 12 | return 0; 13 | } 14 | 15 | void strcpyArray(char *s, char *t) 16 | { 17 | int i; 18 | 19 | i = 0; 20 | while ((s[i] = t[i]) != '\0') 21 | i++; 22 | } 23 | 24 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/case-convert.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void strtolower(const char *src, char *dst) 4 | { 5 | while (*src) { 6 | *dst++ = tolower(*src++); 7 | } 8 | *dst = '\0'; 9 | } 10 | 11 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/getch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define BUFSIZE 100 5 | 6 | int buf[BUFSIZE]; 7 | int bufp = 0; 8 | 9 | int value = EOF; 10 | 11 | int getch(void) 12 | { 13 | return (bufp > 0) ? buf[--bufp] : getchar(); 14 | } 15 | 16 | void ungetch(int c) 17 | { 18 | if (bufp >= BUFSIZE) 19 | printf("ungetch: too many characters\n"); 20 | else 21 | buf[bufp++] = c; 22 | } 23 | 24 | void ungetchs(char s[]) 25 | { 26 | int len = strlen(s); 27 | while (len > 0) { 28 | ungetch(s[--len]); 29 | } 30 | } 31 | 32 | int getchOne(void) 33 | { 34 | if (value != EOF) { 35 | int temp = value; 36 | value = EOF; 37 | return temp; 38 | } 39 | else 40 | return getchar(); 41 | } 42 | 43 | void ungetchOne(int c) 44 | { 45 | if (value != EOF) 46 | printf("ungetchOne: cannot ungetch more char\n"); 47 | else 48 | value = c; 49 | } 50 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/mygetline.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | int mygetline(char s[], int lim) 5 | { 6 | int c, i; 7 | i = 0; 8 | while (--lim > 0 && (c = getchar()) != EOF && c != '\n') 9 | s[i++] = c; 10 | if (c == '\n') 11 | s[i++] = c; 12 | s[i] = '\0'; 13 | return i; 14 | } 15 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/numcmp.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int numcmp(char *s1, char *s2) 4 | { 5 | double v1, v2; 6 | 7 | v1 = atof(s1); 8 | v2 = atof(s2); 9 | if (v1 < v2) 10 | return -1; 11 | else if (v1 > v2) 12 | return 1; 13 | else 14 | return 0; 15 | } 16 | 17 | -------------------------------------------------------------------------------- /chapter-5-pointers-and-arrays/readlines-writelines.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAXLEN 10000 5 | 6 | int readlines(char *lineptr[], int maxlines) 7 | { 8 | int mygetline(char *, int); 9 | char *alloc(int); 10 | 11 | int len, nlines; 12 | char *p, line[MAXLEN]; 13 | nlines = 0; 14 | while ((len = mygetline(line, MAXLEN)) > 0) 15 | if (nlines >= maxlines || (p = alloc(len)) == NULL) 16 | return -1; 17 | else { 18 | line[len-1] = '\0'; 19 | strcpy(p, line); 20 | lineptr[nlines++] = p; 21 | } 22 | 23 | return nlines; 24 | } 25 | 26 | void writelines(char *lineptr[], int nlines) 27 | { 28 | while (nlines-- > 0) 29 | printf("%s\n", *lineptr++); 30 | } 31 | 32 | int mygetline(char *s, int lim) 33 | { 34 | int c; 35 | char *t = s; 36 | while (--lim > 0 && (c = getchar()) != EOF && c != '\n') 37 | *t++ = c; 38 | 39 | if (c == '\n') 40 | *t++ = c; 41 | 42 | *t = '\0'; 43 | return t - s; 44 | } 45 | 46 | -------------------------------------------------------------------------------- /chapter-6-structures/1.structures-and-functions.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define XMAX 100 4 | #define YMAX 100 5 | 6 | #define min(a, b) ((a) < (b) ? (a) : (b)) 7 | #define max(a, b) ((a) > (b) ? (a) : (b)) 8 | 9 | struct point { 10 | int x; 11 | int y; 12 | }; 13 | 14 | struct rect { 15 | struct point pt1; 16 | struct point pt2; 17 | }; 18 | 19 | main() 20 | { 21 | struct rect screen; 22 | struct point middle; 23 | struct point makepoint(int, int); 24 | struct point addpoint(struct point, struct point); 25 | int ptinrect(struct point, struct rect); 26 | struct rect canonrect(struct rect); 27 | 28 | screen.pt1 = makepoint(0, 0); 29 | screen.pt2 = makepoint(XMAX, YMAX); 30 | middle = makepoint((screen.pt1.x + screen.pt2.x) / 2, 31 | (screen.pt1.y + screen.pt2.y) /2); 32 | 33 | printf("middle.x: %d, middle.y: %d\n", middle.x, middle.y); 34 | 35 | struct point p1 = { 5, 5 }; 36 | 37 | p1 = addpoint(p1, middle); 38 | 39 | printf("p1.x: %d, p1.y: %d\n", p1.x, p1.y); 40 | 41 | int p1inscreen = ptinrect(p1, screen); 42 | 43 | printf("p1inscreen: %d\n", p1inscreen); 44 | 45 | struct point p2; 46 | 47 | printf("p2.x: %d, p2.y: %d\n", p2.x, p2.y); 48 | 49 | 50 | struct rect r1 = { 10, 10, 0, 0 }; 51 | 52 | printf("r1.pt1.x: %d, r1.pt1.y: %d, r1.pt2.x: %d, r1.pt2.y: %d\n", 53 | r1.pt1.x, r1.pt1.y, r1.pt2.x, r1.pt2.y); 54 | 55 | r1 = canonrect(r1); 56 | 57 | printf("r1.pt1.x: %d, r1.pt1.y: %d, r1.pt2.x: %d, r1.pt2.y: %d\n", 58 | r1.pt1.x, r1.pt1.y, r1.pt2.x, r1.pt2.y); 59 | 60 | struct rect r2 = { { 20, 0 }, { 0, 20 } }; 61 | 62 | printf("r2.pt1.x: %d, r2.pt1.y: %d, r2.pt2.x: %d, r2.pt2.y: %d\n", 63 | r2.pt1.x, r2.pt1.y, r2.pt2.x, r2.pt2.y); 64 | 65 | r2 = canonrect(r2); 66 | 67 | printf("r2.pt1.x: %d, r2.pt1.y: %d, r2.pt2.x: %d, r2.pt2.y: %d\n", 68 | r2.pt1.x, r2.pt1.y, r2.pt2.x, r2.pt2.y); 69 | 70 | 71 | struct point origin = { 15, 20 }; 72 | struct point *pp; 73 | 74 | pp = &origin; 75 | printf("origin is (%d, %d)\n", (*pp).x, (*pp).y); 76 | printf("origin is (%d, %d)\n", pp->x, pp->y); 77 | 78 | return 0; 79 | } 80 | 81 | struct point makepoint(int x, int y) 82 | { 83 | struct point temp; 84 | 85 | temp.x = x; 86 | temp.y = y; 87 | return temp; 88 | } 89 | 90 | struct point addpoint(struct point p1, struct point p2) 91 | { 92 | p1.x += p2.x; 93 | p1.y += p2.y; 94 | return p1; 95 | } 96 | 97 | int ptinrect(struct point p, struct rect r) 98 | { 99 | return p.x >= r.pt1.x && p.x < r.pt2.x 100 | && p.y >= r.pt1.y && p.y < r.pt2.y; 101 | } 102 | 103 | struct rect canonrect(struct rect r) 104 | { 105 | struct rect temp; 106 | 107 | temp.pt1.x = min(r.pt1.x, r.pt2.x); 108 | temp.pt1.y = min(r.pt1.y, r.pt2.y); 109 | temp.pt2.x = max(r.pt1.x, r.pt2.x); 110 | temp.pt2.y = max(r.pt1.y, r.pt2.y); 111 | return temp; 112 | } 113 | 114 | -------------------------------------------------------------------------------- /chapter-6-structures/2.keywords-count.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAXWORD 100 6 | 7 | struct key { 8 | char *word; 9 | int count; 10 | } keytab[] = { 11 | { "auto", 0 }, { "break", 0 }, { "case", 0 }, { "char", 0 }, 12 | { "const", 0 }, { "continue", 0 }, { "default", 0 }, { "double", 0 }, { "else", 0 }, 13 | { "enum", 0 }, { "extern", 0 }, { "float", 0 }, { "for", 0 }, 14 | { "goto", 0 }, { "if", 0 }, { "int", 0 }, { "long", 0 }, 15 | { "register", 0 }, { "return", 0 }, { "short", 0 }, { "signed", 0 }, 16 | { "sizeof", 0 }, { "static", 0 }, { "struct", 0 }, { "switch", 0 }, 17 | { "typedef", 0 }, { "union", 0 }, { "unsigned", 0 }, { "void", 0 }, 18 | { "volatile", 0 }, { "while", 0 } 19 | }; 20 | 21 | #define NKEYS (sizeof keytab / sizeof keytab[0]) 22 | 23 | int getword(char *, int); 24 | int binsearch(char *, struct key *, int); 25 | 26 | // gcc 2.keyowrds-count.c getch.c 27 | main() 28 | { 29 | int n; 30 | char word[MAXWORD]; 31 | 32 | while (getword(word, MAXWORD) != EOF) 33 | if (isalpha(word[0])) 34 | if ((n = binsearch(word, keytab, NKEYS)) >= 0) 35 | keytab[n].count++; 36 | 37 | for (n = 0; n < NKEYS; n++) 38 | if (keytab[n].count > 0) 39 | printf("%4d %s\n", 40 | keytab[n].count, keytab[n].word); 41 | 42 | return 0; 43 | } 44 | 45 | int binsearch(char *word, struct key tab[], int n) 46 | { 47 | int cond; 48 | int low, high, mid; 49 | 50 | low = 0; 51 | high = n - 1; 52 | while (low <= high) { 53 | mid = (low+high) / 2; 54 | if ((cond = strcmp(word, tab[mid].word)) < 0) 55 | high = mid - 1; 56 | else if (cond > 0) 57 | low = mid + 1; 58 | else 59 | return mid; 60 | } 61 | return -1; 62 | } 63 | 64 | int getword(char *word, int lim) 65 | { 66 | int c, getch(void); 67 | void ungetch(int); 68 | char *w = word; 69 | 70 | while (isspace(c = getch())) 71 | ; 72 | if (c != EOF) 73 | *w++ = c; 74 | if (!isalpha(c)) { 75 | *w = '\0'; 76 | return c; 77 | } 78 | for ( ; --lim > 0; w++) 79 | if (!isalnum(*w = getch())) { 80 | ungetch(*w); 81 | break; 82 | } 83 | *w = '\0'; 84 | return word[0]; 85 | } 86 | 87 | -------------------------------------------------------------------------------- /chapter-6-structures/3.getword.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAXWORD 100 6 | 7 | struct key { 8 | char *word; 9 | int count; 10 | } keytab[] = { 11 | { "auto", 0 }, { "break", 0 }, { "case", 0 }, { "char", 0 }, 12 | { "const", 0 }, { "continue", 0 }, { "default", 0 }, { "double", 0 }, { "else", 0 }, 13 | { "enum", 0 }, { "extern", 0 }, { "float", 0 }, { "for", 0 }, 14 | { "goto", 0 }, { "if", 0 }, { "int", 0 }, { "long", 0 }, 15 | { "register", 0 }, { "return", 0 }, { "short", 0 }, { "signed", 0 }, 16 | { "sizeof", 0 }, { "static", 0 }, { "struct", 0 }, { "switch", 0 }, 17 | { "typedef", 0 }, { "union", 0 }, { "unsigned", 0 }, { "void", 0 }, 18 | { "volatile", 0 }, { "while", 0 } 19 | }; 20 | 21 | #define NKEYS (sizeof keytab / sizeof keytab[0]) 22 | 23 | int getword(char *, int); 24 | int binsearch(char *, struct key *, int); 25 | 26 | // gcc 3.getword.c getch.c 27 | main() 28 | { 29 | int n; 30 | char word[MAXWORD]; 31 | 32 | while (getword(word, MAXWORD) != EOF) { 33 | if (isalpha(word[0])) 34 | if ((n = binsearch(word, keytab, NKEYS)) >= 0) 35 | keytab[n].count++; 36 | } 37 | 38 | for (n = 0; n < NKEYS; n++) 39 | if (keytab[n].count > 0) 40 | printf("%4d %s\n", 41 | keytab[n].count, keytab[n].word); 42 | 43 | return 0; 44 | } 45 | 46 | int binsearch(char *word, struct key tab[], int n) 47 | { 48 | int cond; 49 | int low, high, mid; 50 | 51 | low = 0; 52 | high = n - 1; 53 | while (low <= high) { 54 | mid = (low+high) / 2; 55 | if ((cond = strcmp(word, tab[mid].word)) < 0) 56 | high = mid - 1; 57 | else if (cond > 0) 58 | low = mid + 1; 59 | else 60 | return mid; 61 | } 62 | return -1; 63 | } 64 | 65 | int getword(char *word, int lim) 66 | { 67 | int c, getch(void); 68 | void ungetch(int); 69 | char *w = word; 70 | 71 | while (isspace(c = getch())) 72 | ; 73 | if (c != EOF) 74 | *w++ = c; 75 | 76 | if (c == '/') { 77 | *w = getch(); 78 | if (*w == '/') { 79 | for ( ; --lim > 0; w++) { 80 | if ((*w = getch()) == '\n') { 81 | *++w = '\0'; 82 | return c; 83 | } 84 | } 85 | } else if (*w == '*') { 86 | for ( ; --lim > 0; w++) { 87 | if ((*w = getch()) == '*') { 88 | if ((*++w = getch()) == '/') { 89 | *++w = '\0'; 90 | return c; 91 | } 92 | } 93 | } 94 | } else { 95 | ungetch(*w); 96 | } 97 | } 98 | 99 | if (c == '\'') { 100 | *w++ = getch(); 101 | *w++ = getch(); 102 | *w = '\0'; 103 | return c; 104 | } 105 | 106 | if (c == '"') 107 | for ( ; --lim > 0; w++) 108 | if ((*w = getch()) == '"') { 109 | *++w = '\0'; 110 | return c; 111 | } 112 | 113 | if (!isalpha(c) && c != '_') { 114 | *w = '\0'; 115 | return c; 116 | } 117 | for ( ; --lim > 0; w++) 118 | if (!isalnum(*w = getch()) && *w != '_') { 119 | ungetch(*w); 120 | break; 121 | } 122 | *w = '\0'; 123 | return word[0]; 124 | } 125 | 126 | // for test sizeof return int double register 127 | 128 | /* sizeof struct void while break 129 | */ 130 | 131 | -------------------------------------------------------------------------------- /chapter-6-structures/4.keywords-count-pointer.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAXWORD 100 6 | 7 | struct key { 8 | char *word; 9 | int count; 10 | } keytab[] = { 11 | { "auto", 0 }, { "break", 0 }, { "case", 0 }, { "char", 0 }, 12 | { "enum", 0 }, { "extern", 0 }, { "float", 0 }, { "for", 0 }, 13 | { "goto", 0 }, { "if", 0 }, { "int", 0 }, { "long", 0 }, 14 | { "register", 0 }, { "return", 0 }, { "short", 0 }, { "signed", 0 }, 15 | { "const", 0 }, { "continue", 0 }, { "default", 0 }, { "double", 0 }, 16 | { "else", 0 }, { "sizeof", 0 }, { "static", 0 }, { "struct", 0 }, 17 | { "switch", 0 }, { "typedef", 0 }, { "union", 0 }, { "unsigned", 0 }, 18 | { "void", 0 }, { "volatile", 0 }, { "while", 0 } 19 | }; 20 | 21 | #define NKEYS (sizeof keytab / sizeof keytab[0]) 22 | 23 | int getword(char *, int); 24 | struct key *binsearch(char *, struct key *, int); 25 | void qsort(struct key v[], int, int); 26 | 27 | // gcc 4.keyowrds-count-pointer.c getch.c 28 | main() 29 | { 30 | char word[MAXWORD]; 31 | struct key *p; 32 | 33 | qsort(keytab, 0, NKEYS-1); 34 | 35 | while (getword(word, MAXWORD) != EOF) 36 | if (isalpha(word[0])) 37 | if ((p = binsearch(word, keytab, NKEYS)) != NULL) 38 | p->count++; 39 | 40 | for (p = keytab; p < keytab + NKEYS; p++) 41 | if (p->count > 0) 42 | printf("%4d %s\n", p->count, p->word); 43 | 44 | return 0; 45 | } 46 | 47 | struct key *binsearch(char *word, struct key *tab, int n) 48 | { 49 | int cond; 50 | struct key *low = &tab[0]; 51 | struct key *high = &tab[n]; 52 | struct key *mid; 53 | 54 | while (low < high) { 55 | mid = low + (high-low) / 2; 56 | if ((cond = strcmp(word, mid->word)) < 0) 57 | high = mid; 58 | else if (cond > 0) 59 | low = mid + 1; 60 | else 61 | return mid; 62 | } 63 | return NULL; 64 | } 65 | 66 | int getword(char *word, int lim) 67 | { 68 | int c, getch(void); 69 | void ungetch(int); 70 | char *w = word; 71 | 72 | while (isspace(c = getch())) 73 | ; 74 | if (c != EOF) 75 | *w++ = c; 76 | if (!isalpha(c)) { 77 | *w = '\0'; 78 | return c; 79 | } 80 | for ( ; --lim > 0; w++) 81 | if (!isalnum(*w = getch())) { 82 | ungetch(*w); 83 | break; 84 | } 85 | *w = '\0'; 86 | return word[0]; 87 | } 88 | 89 | void qsort(struct key v[], int left, int right) 90 | { 91 | int i, last; 92 | void swap(struct key v[], int i, int j); 93 | 94 | if (left >= right) 95 | return; 96 | swap(v, left, (left + right) / 2); 97 | last = left; 98 | for (i = left+1; i <= right; i++) 99 | if (strcmp(v[i].word, v[left].word) < 0) 100 | swap(v, ++last, i); 101 | swap(v, left, last); 102 | qsort(v, left, last-1); 103 | qsort(v, last+1, right); 104 | } 105 | 106 | void swap(struct key v[], int i, int j) 107 | { 108 | struct key temp; 109 | 110 | temp = v[i]; 111 | v[i] = v[j]; 112 | v[j] = temp; 113 | } 114 | 115 | -------------------------------------------------------------------------------- /chapter-6-structures/5.words-count-binary-tree.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define MAXWORD 100 7 | 8 | struct tnode { 9 | char *word; 10 | int count; 11 | struct tnode *left; 12 | struct tnode *right; 13 | }; 14 | 15 | struct tnode *addtree(struct tnode *, char *); 16 | void treeprint(struct tnode *); 17 | int getword(char *, int); 18 | 19 | // gcc 5.words-count-binary-tree.c getch.c 20 | main() 21 | { 22 | struct tnode *root; 23 | char word[MAXWORD]; 24 | 25 | root = NULL; 26 | while (getword(word, MAXWORD) != EOF) 27 | if (isalpha(word[0])) 28 | root = addtree(root, word); 29 | treeprint(root); 30 | 31 | return 0; 32 | } 33 | 34 | int getword(char *word, int lim) 35 | { 36 | int c, getch(void); 37 | void ungetch(int); 38 | char *w = word; 39 | 40 | while (isspace(c = getch())) 41 | ; 42 | if (c != EOF) 43 | *w++ = c; 44 | if (!isalpha(c)) { 45 | *w = '\0'; 46 | return c; 47 | } 48 | for ( ; --lim > 0; w++) 49 | if (!isalnum(*w = getch())) { 50 | ungetch(*w); 51 | break; 52 | } 53 | *w = '\0'; 54 | return word[0]; 55 | } 56 | 57 | struct tnode *talloc(void); 58 | char *mystrdup(char *s); 59 | 60 | struct tnode *addtree(struct tnode *p, char *w) 61 | { 62 | int cond; 63 | 64 | if (p == NULL) { 65 | p = talloc(); 66 | p->word = mystrdup(w); 67 | p->count = 1; 68 | p->left = p-> right = NULL; 69 | } else if ((cond = strcmp(w, p->word)) == 0) 70 | p->count++; 71 | else if (cond < 0) 72 | p->left = addtree(p->left, w); 73 | else 74 | p->right = addtree(p->right, w); 75 | return p; 76 | } 77 | 78 | void treeprint(struct tnode *p) 79 | { 80 | if (p != NULL) { 81 | treeprint(p->left); 82 | printf("%4d %s\n", p->count, p->word); 83 | treeprint(p->right); 84 | } 85 | } 86 | 87 | struct tnode *talloc(void) 88 | { 89 | return (struct tnode *) malloc(sizeof(struct tnode)); 90 | } 91 | 92 | char *mystrdup(char *s) 93 | { 94 | char *p; 95 | 96 | p = (char *) malloc(strlen(s)+1); 97 | if (p != NULL) 98 | strcpy(p, s); 99 | 100 | return p; 101 | } 102 | 103 | -------------------------------------------------------------------------------- /chapter-6-structures/6.variables-group.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define MAXWORD 100 7 | 8 | struct tnode { 9 | char *word; 10 | int count; 11 | struct tnode *left; 12 | struct tnode *right; 13 | }; 14 | 15 | struct list { 16 | struct tnode *cur; 17 | struct list *next; 18 | }; 19 | 20 | const char *keywords[] = {"char", "double", "int", "float", "void"}; 21 | 22 | struct tnode *addtree(struct tnode *, char *); 23 | void treeprint(struct tnode *); 24 | int getword(char *, int); 25 | int iskeyword(char *word); 26 | int binsearch(char *word, const char *keywords[], int n); 27 | int getvariable(char *word, int lim); 28 | void addgroup(struct list *, char *, int same_char); 29 | void sort_groups(struct list *tlist, int same_char); 30 | void swap_tree_cur(struct list *pre, struct list *next); 31 | void groupprint(struct list *tlist); 32 | 33 | // gcc 6.variables-group.c getch.c 34 | main(int argc, char *argv[]) 35 | { 36 | int same_char = 1; 37 | if (argc > 1) 38 | same_char = atoi(argv[1]); 39 | 40 | struct list *tlist = malloc(sizeof(struct list)); 41 | tlist->cur = NULL; 42 | tlist->next = NULL; 43 | 44 | struct tnode *root; 45 | char word[MAXWORD]; 46 | 47 | root = NULL; 48 | while (getword(word, MAXWORD) != EOF) 49 | if (iskeyword(word)) { 50 | getvariable(word, MAXWORD); 51 | if (isalpha(word[0])) { 52 | addgroup(tlist, word, same_char); 53 | } 54 | } 55 | sort_groups(tlist, same_char); 56 | groupprint(tlist); 57 | 58 | return 0; 59 | } 60 | 61 | int getword(char *word, int lim) 62 | { 63 | int c, getch(void); 64 | void ungetch(int); 65 | char *w = word; 66 | 67 | while (isspace(c = getch())) 68 | ; 69 | if (c != EOF) 70 | *w++ = c; 71 | if (!isalpha(c)) { 72 | *w = '\0'; 73 | return c; 74 | } 75 | for ( ; --lim > 0; w++) 76 | if (!isalnum(*w = getch())) { 77 | ungetch(*w); 78 | break; 79 | } 80 | *w = '\0'; 81 | return word[0]; 82 | } 83 | 84 | int iskeyword(char *word) 85 | { 86 | if (binsearch(word, keywords, sizeof(keywords) / sizeof(keywords[0])) != -1) 87 | return 1; 88 | else 89 | return 0; 90 | } 91 | 92 | int binsearch(char *word, const char *keywords[], int n) 93 | { 94 | int cond; 95 | int low, high, mid; 96 | 97 | low = 0; 98 | high = n - 1; 99 | while (low <= high) { 100 | mid = (low+high) / 2; 101 | if ((cond = strcmp(word, keywords[mid])) < 0) 102 | high = mid - 1; 103 | else if (cond > 0) 104 | low = mid + 1; 105 | else 106 | return mid; 107 | } 108 | return -1; 109 | } 110 | 111 | int getvariable(char *word, int lim) 112 | { 113 | int c, getch(void); 114 | void ungetch(int); 115 | char *w = word; 116 | 117 | while (isspace(c = getch()) || c == '*') 118 | ; 119 | if (c != EOF) 120 | *w++ = c; 121 | if (!isalpha(c)) { 122 | *w = '\0'; 123 | return c; 124 | } 125 | for ( ; --lim > 0; w++) 126 | if (!isalnum(*w = getch())) { 127 | ungetch(*w); 128 | break; 129 | } 130 | *w = '\0'; 131 | return word[0]; 132 | } 133 | 134 | struct tnode *talloc(void); 135 | char *mystrdup(char *s); 136 | 137 | void addgroup(struct list *tlist, char *word, int same_char) 138 | { 139 | if (tlist->cur == NULL) { 140 | tlist->cur = talloc(); 141 | tlist->cur->word = mystrdup(word); 142 | tlist->cur->count = 1; 143 | tlist->cur->left = tlist->cur->right = NULL; 144 | } else { 145 | struct list *p = tlist, *pre = tlist; 146 | while (p != NULL && p->cur != NULL && strncmp(word, p->cur->word, same_char) != 0) { 147 | pre = p; 148 | p = p->next; 149 | } 150 | if (p == NULL) { 151 | p = malloc(sizeof(struct list)); 152 | p->cur = NULL; 153 | p->next = NULL; 154 | addgroup(p, word, same_char); 155 | pre->next = p; 156 | } else { 157 | addtree(p->cur, word); 158 | } 159 | } 160 | } 161 | 162 | struct tnode *addtree(struct tnode *p, char *w) 163 | { 164 | int cond; 165 | 166 | if (p == NULL) { 167 | p = talloc(); 168 | p->word = mystrdup(w); p->count = 1; 169 | p->left = p-> right = NULL; 170 | } else if ((cond = strcmp(w, p->word)) == 0) 171 | p->count++; 172 | else if (cond < 0) 173 | p->left = addtree(p->left, w); 174 | else 175 | p->right = addtree(p->right, w); 176 | return p; 177 | } 178 | 179 | void treeprint(struct tnode *p) 180 | { 181 | if (p != NULL) { 182 | treeprint(p->left); 183 | printf("%4d %s\n", p->count, p->word); 184 | treeprint(p->right); 185 | } 186 | } 187 | 188 | struct tnode *talloc(void) 189 | { 190 | return (struct tnode *) malloc(sizeof(struct tnode)); 191 | } 192 | 193 | char *mystrdup(char *s) 194 | { 195 | char *p; 196 | 197 | p = (char *) malloc(strlen(s)+1); 198 | if (p != NULL) 199 | strcpy(p, s); 200 | 201 | return p; 202 | } 203 | 204 | void sort_groups(struct list *tlist, int same_char) 205 | { 206 | struct list *pre = tlist; 207 | struct list *p; 208 | int swapped = 0; 209 | while (pre != NULL) { 210 | p = pre; 211 | while (p != NULL && p->next != NULL) { 212 | if (strncmp(p->cur->word, p->next->cur->word, same_char) > 0) { 213 | swap_tree_cur(p, p->next); 214 | swapped = 1; 215 | } 216 | p = p->next; 217 | } 218 | if (swapped == 0) 219 | break; 220 | else 221 | swapped = 0; 222 | } 223 | } 224 | 225 | void swap_tree_cur(struct list *pre, struct list *next) 226 | { 227 | struct tnode *temp; 228 | temp = pre->cur; 229 | pre->cur = next->cur; 230 | next->cur = temp; 231 | } 232 | 233 | void groupprint(struct list *tlist) 234 | { 235 | int i = 0; 236 | struct list *p = tlist; 237 | while (p != NULL) { 238 | printf("Group %d:\n", i++); 239 | treeprint(p->cur); 240 | printf("\n"); 241 | p = p->next; 242 | } 243 | } 244 | 245 | -------------------------------------------------------------------------------- /chapter-6-structures/7.words-appear-lines.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define MAXWORD 100 7 | #define MAX_LINES 100 8 | 9 | struct tnode { 10 | char *word; 11 | int count; 12 | int lines[MAX_LINES]; 13 | struct tnode *left; 14 | struct tnode *right; 15 | }; 16 | 17 | struct tnode *addtree(struct tnode *, char *); 18 | void treeprint(struct tnode *); 19 | int getword(char *, int); 20 | 21 | static int current_line = 1; 22 | 23 | // gcc 7.words-appear-lines.c getch.c 24 | main() 25 | { 26 | struct tnode *root; 27 | char word[MAXWORD]; 28 | 29 | root = NULL; 30 | while (getword(word, MAXWORD) != EOF) 31 | if (isalpha(word[0])) 32 | root = addtree(root, word); 33 | treeprint(root); 34 | 35 | return 0; 36 | } 37 | 38 | int getword(char *word, int lim) 39 | { 40 | int c, getch(void); 41 | void ungetch(int); 42 | char *w = word; 43 | 44 | do { 45 | c = getch(); 46 | if (c == '\n') 47 | ++current_line; 48 | } while (isspace(c)); 49 | 50 | if (c != EOF) 51 | *w++ = c; 52 | if (!isalpha(c)) { 53 | *w = '\0'; 54 | return c; 55 | } 56 | for ( ; --lim > 0; w++) 57 | if (!isalnum(*w = getch()) && *w != '_') { 58 | ungetch(*w); 59 | break; 60 | } 61 | *w = '\0'; 62 | return word[0]; 63 | } 64 | 65 | struct tnode *talloc(void); 66 | char *mystrdup(char *s); 67 | 68 | struct tnode *addtree(struct tnode *p, char *w) 69 | { 70 | int cond; 71 | int i; 72 | 73 | if (p == NULL) { 74 | p = talloc(); 75 | p->word = mystrdup(w); 76 | p->count = 1; 77 | p->lines[0] = current_line; 78 | p->left = p-> right = NULL; 79 | } else if ((cond = strcmp(w, p->word)) == 0) { 80 | p->count++; 81 | i = 0; 82 | while (p->lines[i] != 0) 83 | ++i; 84 | //printf("i: %d\n", i); 85 | p->lines[i] = current_line; 86 | } else if (cond < 0) 87 | p->left = addtree(p->left, w); 88 | else 89 | p->right = addtree(p->right, w); 90 | return p; 91 | } 92 | 93 | void treeprint(struct tnode *p) 94 | { 95 | int i = 0; 96 | if (p != NULL) { 97 | treeprint(p->left); 98 | printf("%4d %s ", p->count, p->word); 99 | while (p->lines[i] != 0 && i < MAX_LINES) 100 | printf("%d ", p->lines[i++]); 101 | printf("\n"); 102 | treeprint(p->right); 103 | } 104 | } 105 | 106 | struct tnode *talloc(void) 107 | { 108 | return (struct tnode *) malloc(sizeof(struct tnode)); 109 | } 110 | 111 | char *mystrdup(char *s) 112 | { 113 | char *p; 114 | 115 | p = (char *) malloc(strlen(s)+1); 116 | if (p != NULL) 117 | strcpy(p, s); 118 | 119 | return p; 120 | } 121 | 122 | -------------------------------------------------------------------------------- /chapter-6-structures/8.table-lookup.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct nlist { 6 | struct nlist *next; 7 | char *name; 8 | char *defn; 9 | }; 10 | 11 | #define HASHSIZE 101 12 | 13 | static struct nlist *hashtab[HASHSIZE]; 14 | 15 | unsigned hash(char *s); 16 | struct nlist *lookup(char *s); 17 | struct nlist *install(char *name, char *defn); 18 | struct nlist *undef(char *name); 19 | 20 | int main() 21 | { 22 | install("name", "Trump"); 23 | struct nlist *n = lookup("name"); 24 | if (n != NULL) 25 | printf("n->defn: %s\n", n->defn); 26 | else 27 | printf("n == NULL\n"); 28 | 29 | install("name", "Obama"); 30 | lookup("test"); 31 | 32 | n = lookup("name"); 33 | printf("n->defn: %s\n", n->defn); 34 | 35 | n = undef("name"); 36 | printf("n->defn: %s\n", n->defn); 37 | free(n->name); 38 | free(n->defn); 39 | free(n); 40 | 41 | n = lookup("name"); 42 | printf("n == NULL: %d\n", n == NULL); 43 | 44 | return 0; 45 | } 46 | 47 | unsigned hash(char *s) 48 | { 49 | unsigned hashval; 50 | for (hashval = 0; *s != '\0'; ++s) 51 | hashval = *s + 31 * hashval; 52 | return hashval % HASHSIZE; 53 | } 54 | 55 | struct nlist *lookup(char *s) 56 | { 57 | struct nlist *np; 58 | 59 | for (np = hashtab[hash(s)]; np != NULL; np = np->next) { 60 | if (strcmp(s, np->name) == 0) 61 | return np; 62 | } 63 | return NULL; 64 | } 65 | 66 | struct nlist *install(char *name, char *defn) 67 | { 68 | struct nlist *np; 69 | unsigned hashval; 70 | 71 | if ((np = lookup(name)) == NULL) { 72 | np = (struct nlist *) malloc(sizeof(*np)); 73 | if (np == NULL || (np->name = strdup(name)) == NULL) 74 | return NULL; 75 | hashval = hash(name); 76 | np->next = hashtab[hashval]; 77 | hashtab[hashval] = np; 78 | } else 79 | free((void *) np->defn); 80 | 81 | if ((np->defn = strdup(defn)) == NULL) 82 | return NULL; 83 | return np; 84 | } 85 | 86 | struct nlist *undef(char *name) 87 | { 88 | struct nlist *np; 89 | 90 | if ((np = lookup(name)) == NULL) 91 | return NULL; 92 | 93 | unsigned hashval = hash(name); 94 | hashtab[hashval] = NULL; 95 | 96 | return np; 97 | } 98 | 99 | -------------------------------------------------------------------------------- /chapter-6-structures/getch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define BUFSIZE 100 5 | 6 | int buf[BUFSIZE]; 7 | int bufp = 0; 8 | 9 | int value = EOF; 10 | 11 | int getch(void) 12 | { 13 | return (bufp > 0) ? buf[--bufp] : getchar(); 14 | } 15 | 16 | void ungetch(int c) 17 | { 18 | if (bufp >= BUFSIZE) 19 | printf("ungetch: too many characters\n"); 20 | else 21 | buf[bufp++] = c; 22 | } 23 | 24 | void ungetchs(char s[]) 25 | { 26 | int len = strlen(s); 27 | while (len > 0) { 28 | ungetch(s[--len]); 29 | } 30 | } 31 | 32 | int getchOne(void) 33 | { 34 | if (value != EOF) { 35 | int temp = value; 36 | value = EOF; 37 | return temp; 38 | } 39 | else 40 | return getchar(); 41 | } 42 | 43 | void ungetchOne(int c) 44 | { 45 | if (value != EOF) 46 | printf("ungetchOne: cannot ungetch more char\n"); 47 | else 48 | value = c; 49 | } 50 | -------------------------------------------------------------------------------- /chapter-7-input-and-output/cat-v1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main(int argc, char *argv[]) 4 | { 5 | FILE *fp; 6 | void filecopy(FILE *, FILE *); 7 | 8 | if (argc == 1) 9 | filecopy(stdin, stdout); 10 | else 11 | while (--argc > 0) 12 | if ((fp = fopen(*++argv, "r")) == NULL) { 13 | printf("cat: can't open %s\n", *argv); 14 | return 1; 15 | } else { 16 | filecopy(fp, stdout); 17 | fclose(fp); 18 | } 19 | 20 | return 0; 21 | } 22 | 23 | void filecopy(FILE *ifp, FILE *ofp) 24 | { 25 | int c; 26 | 27 | while ((c = getc(ifp)) != EOF) 28 | putc(c, ofp); 29 | } 30 | 31 | -------------------------------------------------------------------------------- /chapter-7-input-and-output/cat-v2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | main(int argc, char *argv[]) 5 | { 6 | FILE *fp; 7 | void filecopy(FILE *, FILE *); 8 | char *prog = argv[0]; 9 | 10 | if (argc == 1) 11 | filecopy(stdin, stdout); 12 | else 13 | while (--argc > 0) 14 | if ((fp = fopen(*++argv, "r")) == NULL) { 15 | fprintf(stderr, "%s: can't open %s\n", prog, *argv); 16 | exit(1); 17 | } else { 18 | filecopy(fp, stdout); 19 | fclose(fp); 20 | } 21 | 22 | if (ferror(stdout)) { 23 | fprintf(stderr, "%s: error writing stdout\n", prog); 24 | exit(2); 25 | } 26 | 27 | exit(0); 28 | } 29 | 30 | void filecopy(FILE *ifp, FILE *ofp) 31 | { 32 | int c; 33 | 34 | while ((c = getc(ifp)) != EOF) 35 | putc(c, ofp); 36 | } 37 | 38 | -------------------------------------------------------------------------------- /chapter-7-input-and-output/minprintf.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void minprintf(char *fmt, ...); 5 | 6 | int main() 7 | { 8 | minprintf("int: %d, double: %f, string: %s\n", 1, 0.123, "Hello"); 9 | 10 | return 0; 11 | } 12 | 13 | void minprintf(char *fmt, ...) 14 | { 15 | va_list ap; 16 | char *p, *sval; 17 | int ival; 18 | double dval; 19 | 20 | va_start(ap, fmt); 21 | for (p = fmt; *p; p++) { 22 | if (*p != '%') { 23 | putchar(*p); 24 | continue; 25 | } 26 | switch(*++p) { 27 | case 'd': 28 | ival = va_arg(ap, int); 29 | printf("%d", ival); 30 | break; 31 | case 'f': 32 | dval = va_arg(ap, double); 33 | printf("%f", dval); 34 | break; 35 | case 's': 36 | for (sval = va_arg(ap, char *); *sval; sval++) 37 | putchar(*sval); 38 | break; 39 | default: 40 | putchar(*p); 41 | break; 42 | } 43 | } 44 | va_end(ap); 45 | } 46 | 47 | -------------------------------------------------------------------------------- /chapter-7-input-and-output/scanf-sample.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | double sum, v; 6 | 7 | sum = 0; 8 | while (scanf("%1f", &v) == 1) 9 | printf("\t%.2f\n", sum += v); 10 | return 0; 11 | } 12 | 13 | -------------------------------------------------------------------------------- /chapter-8-the-unix-system-interface/cp.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define PERMS 0666 8 | 9 | void error(char *fmt, ...); 10 | 11 | main(int argc, char *argv[]) 12 | { 13 | int f1, f2, n; 14 | char buf[BUFSIZ]; 15 | 16 | if (argc != 3) 17 | error("usage: cp from to"); 18 | if ((f1 = open(argv[1], O_RDONLY, 0)) == -1) 19 | error("cp: can't open %s", argv[1]); 20 | if ((f2 = open(argv[2], PERMS, 0)) == -1) 21 | error("cp: can't create %s, mode %03o", argv[2], PERMS); 22 | 23 | while ((n = read(f1, buf, BUFSIZ)) > 0) 24 | if (write(f2, buf, n) != n) 25 | error("cp: write error on file %s", argv[2]); 26 | 27 | return 0; 28 | } 29 | 30 | void error(char *fmt, ...) 31 | { 32 | va_list args; 33 | 34 | va_start(args, fmt); 35 | fprintf(stderr, "error: "); 36 | vfprintf(stderr, fmt, args); 37 | fprintf(stderr, "\n"); 38 | va_end(args); 39 | exit(1); 40 | } 41 | 42 | -------------------------------------------------------------------------------- /chapter-8-the-unix-system-interface/dirent.h: -------------------------------------------------------------------------------- 1 | typedef struct { 2 | long ino; 3 | char name[NAME_MAX+1]; 4 | } Dirent; 5 | 6 | typedef struct { 7 | int fd; 8 | Dirent d; 9 | } DIR; 10 | 11 | DIR *opendir(char *dirname); 12 | Dirent *readdir(DIR *dfd); 13 | void closedir(DIR *dfd); 14 | 15 | -------------------------------------------------------------------------------- /chapter-8-the-unix-system-interface/fopen.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | //#define NULL 0 7 | #define EOF (-1) 8 | #define BUFSIZ 1024 9 | #define OPEN_MAX 20 10 | 11 | #define PERMS 0666 12 | 13 | typedef struct _iobuf { 14 | int cnt; 15 | char *ptr; 16 | char *base; 17 | int flag; 18 | int fd; 19 | } FILE; 20 | 21 | FILE _iob[OPEN_MAX]; 22 | 23 | enum _flags { 24 | _READ = 01, 25 | _WRITE = 02, 26 | _UNBUF = 04, 27 | _EOF = 010, 28 | _ERR = 020 29 | }; 30 | 31 | FILE *fopen(char *name, char *mode); 32 | int _fillbuf(FILE *fp); 33 | 34 | int main() 35 | { 36 | FILE *fp = fopen("fopen.c", "rw"); 37 | assert(fp != NULL); 38 | return 0; 39 | } 40 | 41 | FILE *fopen(char *name, char *mode) 42 | { 43 | int fd; 44 | FILE *fp; 45 | 46 | if (*mode != 'r' && *mode != 'w' && *mode != 'a') 47 | return NULL; 48 | for (fp = _iob; fp < _iob + OPEN_MAX; fp++) 49 | if ((fp->flag & (_READ | _WRITE)) == 0) 50 | break; 51 | if (fp >= _iob + OPEN_MAX) 52 | return NULL; 53 | 54 | if (*mode == 'w') 55 | fd = creat(name, PERMS); 56 | else if (*mode == 'a') { 57 | if ((fd = open(name, O_WRONLY, 0)) == -1) 58 | fd = creat(name, PERMS); 59 | lseek(fd, 0L, 2); 60 | } else 61 | fd = open(name, O_RDONLY, 0); 62 | if (fd == -1) 63 | return NULL; 64 | fp->fd = fd; 65 | fp->cnt = 0; 66 | fp->base = NULL; 67 | fp->flag = (*mode == 'r') ? _READ : _WRITE; 68 | return fp; 69 | } 70 | 71 | int _fillbuf(FILE *fp) 72 | { 73 | int bufsize; 74 | 75 | if ((fp->flag & (_READ | EOF | _ERR)) != _READ) 76 | return EOF; 77 | bufsize = (fp->flag & _UNBUF) ? 1 : BUFSIZ; 78 | if (fp->base == NULL) 79 | if ((fp->base = (char *) malloc(bufsize)) == NULL) 80 | return EOF; 81 | fp->ptr = fp->base; 82 | fp->cnt = read(fp->fd, fp->ptr, bufsize); 83 | if (--fp->cnt < 0) { 84 | if (fp->cnt == -1) 85 | fp->flag |= _EOF; 86 | else 87 | fp->flag |= _ERR; 88 | fp->cnt = 0; 89 | return EOF; 90 | } 91 | return (unsigned char) *fp->ptr++; 92 | } 93 | 94 | FILE _iob[OPEN_MAX] = { 95 | { 0, (char *) 0, (char *) 0, _READ, 0 }, 96 | { 0, (char *) 0, (char *) 0, _WRITE, 1 }, 97 | { 0, (char *) 0, (char *) 0, _WRITE | _UNBUF, 2 }, 98 | }; 99 | 100 | -------------------------------------------------------------------------------- /chapter-8-the-unix-system-interface/fsize.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include "dirent.h" 8 | 9 | void fsize(char *); 10 | 11 | main (int argc, char **argv) 12 | { 13 | if (argc == 1) 14 | fsize("."); 15 | else 16 | while (--argc > 0) 17 | fsize(*++argv); 18 | return 0; 19 | } 20 | 21 | int stat(char *, struct stat *); 22 | void dirwalk(char *, void (*fcn)(char *)); 23 | 24 | void fsize(char *name) 25 | { 26 | struct stat stbuf; 27 | 28 | if (stat(name, &stbuf) == -1) { 29 | fprintf(stderr, "fsize: can't access %s\n", name); 30 | return; 31 | } 32 | if ((stbuf.st_mode & S_IFMT) == S_IFDIR) 33 | dirwalk(name, fsize); 34 | printf("%8ld %s\n", stbuf.st_size, name); 35 | } 36 | 37 | #define MAX_PATH 1024 38 | 39 | void dirwalk(char *dir, void (*fcn)(char *)) 40 | { 41 | char name[MAX_PATH]; 42 | Dirent *dp; 43 | DIR *dfd; 44 | 45 | if ((dfd = opendir(dir)) == NULL) { 46 | fprintf(stderr, "dirwalk: can't open %s\n", dir); 47 | return; 48 | } 49 | while ((dp = readdir(dfd)) != NULL) { 50 | if (strcmp(dp->name, ".") == 0 51 | || strcmp(dp->name, "..") == 0) 52 | continue; 53 | if (strlen(dir) + strlen(dp->name) + 2 > sizeof(name)) 54 | fprintf(stderr, "dirwalk: name %s/%s too long\n", 55 | dir, dp->name); 56 | else { 57 | sprintf(name, "%s/%s", dir, dp->name); 58 | (*fcn)(name); 59 | } 60 | } 61 | closedir(dfd); 62 | } 63 | 64 | int fstat(int fd, struct stat *); 65 | 66 | DIR *opendir(char *dirname) 67 | { 68 | int fd; 69 | struct stat stbuf; 70 | DIR *dp; 71 | 72 | if ((fd = open(dirname, O_RDONLY, 0)) == -1 73 | || fstat(fd, &stbuf) == -1 74 | || (stbuf.st_mode & S_IFMT) != S_IFDIR 75 | || (dp = (DIR *) malloc(sizeof(DIR))) == NULL) 76 | return NULL; 77 | dp->fd = fd; 78 | return dp; 79 | } 80 | 81 | void closedir(DIR *dp) 82 | { 83 | if (dp) { 84 | close(dp->fd); 85 | free(dp); 86 | } 87 | } 88 | 89 | #include 90 | 91 | Dirent *readdir(DIR *dp) 92 | { 93 | struct direct dirbuf; 94 | static Dirent d; 95 | 96 | while (read(dp->fd, (char *) &dirbuf, sizeof(dirbuf)) 97 | == sizeof(dirbuf)) { 98 | if (dirbuf.d_ino == 0) 99 | continue; 100 | d.ino = dirbuf.d_ino; 101 | strncpy(d.name, dirbuf.d_name, DIRSIZ); 102 | d.name[DIRSIZ] = '\0'; 103 | return &d; 104 | } 105 | return NULL; 106 | } 107 | 108 | -------------------------------------------------------------------------------- /chapter-8-the-unix-system-interface/malloc.c: -------------------------------------------------------------------------------- 1 | typedef long Align; /* for alignment to long boundary */ 2 | 3 | union header { /* block header: */ 4 | struct { 5 | union header *ptr; /* next block if on free list */ 6 | unsigned size; /* size of this block */ 7 | } s; 8 | Align x; /* force alignment of blocks */ 9 | }; 10 | 11 | typedef union header Header; 12 | 13 | 14 | static Header base; /* empty list to get started */ 15 | static Header *freep = NULL; /* start of free list */ 16 | 17 | /* malloc: general-purpose storage allocator */ 18 | void *malloc(unsigned nbytes) 19 | { 20 | Header *p, *prevp; 21 | Header *morecore(unsigned); 22 | unsigned nunits; 23 | 24 | nunits = (nbytes+sizeof(Header)-1) / sizeof(Header) + 1; 25 | if ((prevp = freep) == NULL) { /* no free list yet */ 26 | base.s.ptr = freep = prevp = &base; 27 | base.s.size = 0; 28 | } 29 | for (p = prevp->s.ptr; ; prevp = p, p = p->s.ptr) { 30 | if (p->s.size >= nunits) { /* big enough */ 31 | if (p->s.size == nunits) /* exactly */ 32 | prevp->s.ptr = p->s.ptr; 33 | else { /* allocate tail end */ 34 | p->s.size -= nunits; 35 | p += p->s.size; 36 | p->s.size = nunits; 37 | } 38 | freep = prevp; 39 | return (void *)(p+1); 40 | } 41 | if (p == freep) /* wrapped around free list */ 42 | if ((p = morecore(nunits)) == NULL) 43 | return NULL; /* none left */ 44 | } 45 | } 46 | 47 | #define NALLOC 1024 /* minimum units to request */ 48 | 49 | /* morecore: ask system for more memory */ 50 | static Header *morecore(unsigned nu) 51 | { 52 | char *cp, *sbrk(int); 53 | Header *up; 54 | 55 | if (nu < NALLOC) 56 | nu = NALLOC; 57 | cp = sbrk(nu * sizeof(Header)); 58 | if (cp == (char *) - 1) /* no space at all */ 59 | return NULL; 60 | up = (Header *) cp; 61 | up->s.size = nu; 62 | free((void *)(up+1)); 63 | return freep; 64 | } 65 | 66 | /* free: put block ap in free list */ 67 | void free(void *ap) 68 | { 69 | Header *bp, *p; 70 | 71 | bp = (Header *)ap - 1; 72 | for (p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 73 | if (p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 74 | break; 75 | 76 | if (bp + bp->s.size == p->s.ptr) { 77 | bp->s.size += p->s.ptr->s.size; 78 | bp->s.ptr = p->s.ptr->s.ptr; 79 | } else 80 | bp->s.ptr = p->s.ptr; 81 | 82 | if (p + p->s.size == bp) { 83 | p->s.size += bp->s.size; 84 | p->s.ptr = bp->s.ptr; 85 | } else 86 | p->s.ptr = bp; 87 | freep = p; 88 | } 89 | 90 | -------------------------------------------------------------------------------- /chapter-8-the-unix-system-interface/sys-copy.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | main() 5 | { 6 | char buf[BUFSIZ]; 7 | int n; 8 | 9 | while ((n = read(0, buf, BUFSIZ)) > 0) 10 | write(1, buf, n); 11 | return 0; 12 | } 13 | 14 | --------------------------------------------------------------------------------