More to come...
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

329 line
15KB

  1. #ifndef CHAPTER_1_SOURCE
  2. #define CHAPTER_1_SOURCE
  3. #include <stdlib.h> // We'll need this header file for malloc, calloc, realloc, free, atexit, rand and exit (some will be used in future chapters).
  4. #include <fcntl.h> // This one for open and 'O_' flags.
  5. #include <unistd.h> // And this one for read, write, close and lseek.
  6. #include "chapter_1.h" // Get used to this... We're pasting macros, enumerations and function declarations again...
  7. int character_is_uppercase (char character) { // Returns a boolean value, aka FALSE or TRUE, aka 0 or 1...
  8. return ((int) ((character >= 'A') && (character <= 'Z')));
  9. }
  10. int character_is_lowercase (char character) {
  11. return ((int) ((character >= 'a') && (character <= 'z')));
  12. }
  13. int character_is_digit (char character) {
  14. return ((int) ((character >= '0') && (character <= '9')));
  15. }
  16. int character_is_blank (char character) { // Standard implementation also considers vertical tab and form feed as blank, we don't...
  17. return ((int) ((character == ' ') || (character == CHARACTER_TAB_HORIZONTAL) || (character == CHARACTER_CARRIAGE_RETURN) || (character == CHARACTER_LINE_FEED)));
  18. // If you like smaller line length limit, you can align it like this:
  19. // return ((character == ' ')
  20. // || (character == CHARACTER_TAB_HORIZONTAL)
  21. // || (character == CHARACTER_CARRIAGE_RETURN)
  22. // || (character == CHARACTER_LINE_FEED));
  23. // Or:
  24. // return ((character == ' ') ||
  25. // (character == CHARACTER_TAB_HORIZONTAL) ||
  26. // (character == CHARACTER_CARRIAGE_RETURN) ||
  27. // (character == CHARACTER_LINE_FEED));
  28. // Or even use literal characters:
  29. // return ((character == ' ') ||
  30. // (character == '\t') ||
  31. // (character == '\r') ||
  32. // (character == '\n'));
  33. }
  34. int character_is_alpha (char character) { // Returns TRUE / 1 or FALSE / 0 depending on if the character is either uppercase or lowercase.
  35. return ((character_is_uppercase (character) != 0) || (character_is_lowercase (character) != 0));
  36. }
  37. int character_is_symbol (char character) { // Returns TRUE / 1 if character is one of the characters in that string (array of characters), otherwise it returns FALSE / 0.
  38. return (character_compare_array (character, "~!@#$%^&*()+{}|:\"<>?`-=[]\\;',./"));
  39. }
  40. int character_is_visible (char character) { // This is visible (printable) character range, and space is included in there.
  41. return ((int) ((character >= ' ') && (character <= '~')));
  42. }
  43. int character_is_invisible (char character) { // If character is not visible, then guess what? It's invisible.
  44. return (character_is_visible (character) == FALSE);
  45. }
  46. int character_is_escape (char character) { // We might use this function...
  47. return ((int) (character == CHARACTER_ESCAPE));
  48. }
  49. int character_is_underscore (char character) { // I don't even know if I'll ever use this one, we'll see, I'm in the process of writing this "book"...
  50. return ((int) (character == '_'));
  51. }
  52. int character_is_hexadecimal (char character) { // Same as function 'character_is_symbol', but for hexadecimal digits.
  53. return (character_compare_array (character, "0123456789ABCDEF"));
  54. }
  55. /*
  56. Now, we can see how function 'character_compare_array' was implemented, but know that it could be even shorter, like you see below. However, I really think it's for the best to
  57. use curly and round braces, when even the compiler won't warn about them. You can easily see the scope of something if you have a text editor capable of highlighting matching
  58. braces, and almost all of them have that feature. Also, don't be afraid of longer lines of code. You can even enable word-wrapping in your ed text editor running on Commodore 64
  59. with 128 GiB of RAM. Just focus more on what you're doing, don't limit yourself to mere 80 characters per line.
  60. @C
  61. int character_compare_array (char character, char * character_array) {
  62. for (; * character_array != CHARACTER_NULL; ++character_array)
  63. if (character == * character_array)
  64. return (TRUE);
  65. return (FALSE);
  66. }
  67. @
  68. */
  69. int character_compare_array (char character, char * character_array) { // I didn't use name "string", but "character_array", to explicitly show the intention of argument.
  70. int offset;
  71. for (offset = 0; offset != string_length (character_array); ++offset) { // We iterate through string (character array!) and return TRUE / 1 if we found it.
  72. if (character == character_array [offset]) { // If we don't find it in that string, we return FALSE / 0 since it's not there.
  73. return (TRUE); // Note that we could do this without the variable 'offset', similar to string functions.
  74. }
  75. }
  76. return (FALSE);
  77. }
  78. int character_count (char * string, char character, int from, int to, char stop) { // This function seem trickier to understand, but it's nothing special if you think about it.
  79. int count;
  80. for (count = 0; (from != to) && (string [from] != stop); from += ((to < from) ? -1 : 1)) { // We want to know how many 'character's are in our 'string'.
  81. count += (int) ((string [from] == character) || (character == '\0')); // This covers searching forward and backward, depending on 'from' and 'to'.
  82. }
  83. return (count); // And we found our count!
  84. }
  85. /*
  86. You can see important information about some functions on manual pages in every Linux distro, with 'man ([optional] number) function_name', for example 'man 2 open', and I'll list
  87. few important ones down below with some copy & paste magic, but I'll keep it short.
  88. @C
  89. #include <sys/types.h> // Core types.
  90. #include <sys/stat.h> // Core something, I don't even know...
  91. #include <fcntl.h> // Few system calls.
  92. int open (const char * pathname, int flags );
  93. int open (const char * pathname, int flags, mode_t mode);
  94. int creat (const char * pathname, mode_t mode);
  95. int openat (int dirfd, const char * pathname, int flags );
  96. int openat (int dirfd, const char * pathname, int flags, mode_t mode);
  97. // Some commonly used file flags (modes, one of the first three must always be present in mode mask):
  98. // - O_RDONLY: Open or create file as 'read only', prohibit writing to that file.
  99. // - O_WRONLY: Open or create file as 'write only', so you have permission to modify it.
  100. // - O_RDWR: Open or create file as 'read and write', so you can do whatever you want with it...
  101. // - O_APPEND: Before each write system call, the file offset is positioned at the end of the file, as if with lseek system call. Like, continue writing...
  102. // - O_CREAT: If path name doesn't exist, create a new file with the name you specified. The owner of the new file is set to the effective user ID of the process.
  103. // - O_TRUNC: If the file already exists and is a regular file and the access mode allows writing (is O_RDWR or O_WRONLY) it will be truncated to length 0.
  104. @
  105. There's a lot more to read in manual pages, about various functions and libraries, they are old (and somewhat outdated, since not everyone use them nowdays, and some don't even
  106. update them) source of information, but can be good for standard library. Also keep in mind that most functions below return -1 on error.
  107. */
  108. int file_open (char * name, int mode) {
  109. int descriptor = -1; // Assume error value as default.
  110. fatal_failure (name == NULL, "file_open: Failed to open file, name is null pointer."); // We must provide non-null address.
  111. fatal_failure ((descriptor = open (name, mode)) == -1, "file_open: Failed to open file, function open returned invalid descriptor."); // We abort of 'open' error...
  112. // We could write something like this too:
  113. // descriptor = open (name, mode);
  114. // fatal_failure (descriptor == -1, "file_open: Failed to open file, function open returned invalid descriptor.");
  115. // Or align it to break two longer function arguments:
  116. // fatal_failure ((descriptor = open (name, mode)) == -1,
  117. // "file_open: Failed to open file, function open returned invalid descriptor.");
  118. // As you can see, if you want to inline variable assignment, you must use braces, like I did in uncommented example.
  119. // And don't confuse '==' equality comparison and '=' assignment operators!
  120. return (descriptor); // Return opened file descriptor.
  121. }
  122. int file_close (int file) {
  123. fatal_failure (file == -1, "file_close: Failed to close file, invalid file descriptor."); // If 'file' was already closed or corrupted, we abort.
  124. fatal_failure (close (file) == -1, "file_close: Failed to close file, function close returned invalid code."); // Keep in mind that this isn't always safe.
  125. return (-1);
  126. }
  127. void file_read (int file, void * data, int size) {
  128. fatal_failure (file == -1, "file_read: Failed to read from file, invalid descriptor."); // We'll comment this out once, since it's all similar with 'file_write'.
  129. fatal_failure (data == NULL, "file_read: Failed to read from file, data is null pointer."); // This function is very similar to 'in', but it accepts a file descriptor.
  130. fatal_failure (size == 0, "file_read: Failed to read from file, size is zero."); // That means we handle the files, not standard input or output.
  131. (void) read (file, data, (unsigned long int) size); // If there was no errors, we read, and don't check for errors at all...
  132. }
  133. void file_write (int file, void * data, int size) {
  134. fatal_failure (file == -1, "file_write: Failed to write to file, invalid descriptor.");
  135. fatal_failure (data == NULL, "file_write: Failed to write to file, data is null pointer.");
  136. fatal_failure (size == 0, "file_write: Failed to write to file, size is zero.");
  137. (void) write (file, data, (unsigned long int) size);
  138. }
  139. int file_seek (int file, int whence) {
  140. fatal_failure (file == -1, "file_seek: Failed to seek in file, invalid descriptor."); // Make sure we have a valid file descriptor (it's also unsafe to assume it)...
  141. return ((int) lseek (file, 0, whence)); // Keep in mind that C isn't safe language. It's safe only if you use your brain.
  142. }
  143. int file_size (char * name) {
  144. int size = -1; // Lets just assume that everything is wrong, everything falls apart...
  145. int file = -1; // Everything is just -1 around us...
  146. file = file_open (name, O_RDONLY); // We open a file to read it.
  147. size = (int) lseek (file, 0, SEEK_END); // We set the offset to the end of the file.
  148. fatal_failure (size == -1, "file_size: Failed to get size of file, invalid file size."); // Again, error of 'lseek' would be -1, so we check for that...
  149. file = file_close (file); // We close the file, meaning we didn't edit it.
  150. return (size); // And we return file size in bytes.
  151. }
  152. /*
  153. Lets pretend that each file type has only one extension and save our selves from headaches. Fuck C++ with it's 10 extensions like '.cpp', '.c++', '.cxx', '.cc', and variations for
  154. header files, with prefix 'h', it's cancer. Why the extension wasn't just '.c=c+1', huh?
  155. */
  156. int file_type (char * name) {
  157. // Keep in mind that I'm intentionally being inconsistent, so you can see several ways to properly align your code, readability is the key to safety!
  158. // Spacing between separate strings in array below is 10 characters, including comma and double quotes, and I "joined" curly braces too, it fits in 180 characters.
  159. // You could break it up on curly braces, or put each string in it's own line if you wanted.
  160. char * file_type_data [FILE_TYPE_COUNT] = { ".txt", ".s", ".fasm", ".gasm", ".nasm", ".yasm", ".c", ".h", ".adb", ".ads", ".cpp", ".hpp" };
  161. int type;
  162. for (; * name != '.'; ++name); // We offset the 'name' until we reach fullstop character.
  163. for (type = 0; type != FILE_TYPE_COUNT; ++type) { // Then we check if it's one from this array by comparing them sequentially.
  164. if (string_compare (name, file_type_data [type]) != 0) { // If it is, we return the value of enumeration of file types.
  165. return (type);
  166. }
  167. }
  168. return (-1); // If it's not in array, we return -1, so we don't access the wrong value in some other array.
  169. }
  170. char * file_record (char * name) {
  171. int file = -1; // You can also initialize local variables in this way.
  172. int size = -1;
  173. char * data = NULL;
  174. fatal_failure (name == NULL, "file_import: Failed to import file, name is null pointer."); // We should abort if the file name is null pointer.
  175. file = file_open (name, O_RDONLY); // Again, we open the file just in order to read it.
  176. size = file_size (name) + 1; // We do it again, but only to get it's size and then increment it.
  177. data = allocate (size); // And we allocate new memory for data in that file.
  178. file_read (file, data, size - 1); // Rest if obvious. This could be implemented smarter. Try to notice why.
  179. file = file_close (file);
  180. return (data); // We return pointer to new memory, but remember, we have to free it later.
  181. }
  182. /*
  183. I won't cover next two functions at this point, because they might be harder to understand, but if you feel confident, try to guess what they do...
  184. */
  185. char * number_to_string (int number) {
  186. int i, sign;
  187. static char string [32];
  188. for (i = 0; i != 32; ++i) {
  189. string [i] = CHARACTER_NULL;
  190. }
  191. if (number == 0) {
  192. string [0] = '0';
  193. string [1] = CHARACTER_NULL;
  194. return (string);
  195. }
  196. if (number < 0) {
  197. number *= -1;
  198. sign = 1;
  199. } else {
  200. sign = 0;
  201. }
  202. for (i = (string [0] == '-'); number != 0; ++i) {
  203. string [i] = (char) (number % 10) + '0';
  204. number /= 10;
  205. }
  206. if (sign != 0) {
  207. string [i] = '-';
  208. ++i;
  209. }
  210. string [i] = CHARACTER_NULL;
  211. string_reverse (string);
  212. return (string);
  213. }
  214. char * format_to_string (int number, int sign, int base, int amount, char character) {
  215. int i;
  216. static char string [32];
  217. for (i = 0; i != 32; ++i) {
  218. string [i] = CHARACTER_NULL;
  219. }
  220. if (number == 0) {
  221. string [0] = '0';
  222. string [1] = CHARACTER_NULL;
  223. string_realign (string, amount, character);
  224. return (string);
  225. }
  226. if (number < 0) {
  227. number *= -1;
  228. }
  229. for (i = (string [0] == '-'); number != 0; ++i) {
  230. string [i] = "0123456789ABCDEF" [number % base];
  231. number /= base;
  232. }
  233. if (sign != 0) {
  234. string [i] = '-';
  235. ++i;
  236. }
  237. string [i] = CHARACTER_NULL;
  238. string_reverse (string);
  239. string_realign (string, amount, character);
  240. return (string);
  241. }
  242. int randomize (int minimum, int maximum) { // Now, we're simply returning random integer between 'minimum' and 'maximum', inclusively.
  243. return (rand () % (maximum - minimum + 1) + minimum);
  244. }
  245. #endif