From 102341d7ae8793c29d44fa416d3b5b797d1eca3e Mon Sep 17 00:00:00 2001 From: Clay Smith Date: Tue, 1 Aug 2023 01:09:09 -0500 Subject: First commit --- add2Nums.c | 6 + add2Nums2.c | 8 ++ arrays.c | 31 +++++ c_remove_function.c | 23 ++++ characters.c | 28 +++++ command_arguments_inC.c | 19 ++++ copy_static_array_to_dynamic_array.c | 72 ++++++++++++ enum_tutorials.c | 17 +++ file_operations.c | 101 +++++++++++++++++ file_operations_test.txt | 31 +++++ for_while.c | 36 ++++++ fork_bomb.c | 10 ++ function_pointers.c | 14 +++ gtk_first_window.c | 28 +++++ i_vs_d_printf_scanf.c | 15 +++ including_printf.c | 20 ++++ my_atoi.c | 192 +++++++++++++++++++++++++++++++ my_atoi.h | 8 ++ my_atoi_using.c | 17 +++ nesting_tutorial.c | 58 ++++++++++ passing_arrays.c | 62 ++++++++++ password_tutorial.c | 31 +++++ printf_vs_snprintf_plus_write.c | 29 +++++ printf_with_pointer.c | 11 ++ return_bad.c | 4 + reverse_string.c | 28 +++++ scope_tutorial/1.c | 43 +++++++ scope_tutorial/2.c | 15 +++ scope_tutorial/2.o | Bin 0 -> 536 bytes scope_tutorial/Makefile | 2 + scope_tutorial/a.out | Bin 0 -> 33666 bytes scope_tutorial/header.h | 4 + stack.c | 26 +++++ strings.c | 28 +++++ strings_misc.c | 33 ++++++ test.php | 13 +++ test_unicode.c | 16 +++ testing_strings_versus_arrays.c | 12 ++ text.txt | 213 +++++++++++++++++++++++++++++++++++ threads.c | 63 +++++++++++ time.c | 28 +++++ understanding_chars.c | 29 +++++ understanding_scope.c | 14 +++ understanding_scope.h | 4 + understanding_scope.hza | Bin 0 -> 505256 bytes understanding_scope_1.c | 21 ++++ variable_argument_functions.c | 108 ++++++++++++++++++ variable_argument_functions2.c | 41 +++++++ void_tutorial.c | 14 +++ 49 files changed, 1626 insertions(+) create mode 100644 add2Nums.c create mode 100644 add2Nums2.c create mode 100644 arrays.c create mode 100644 c_remove_function.c create mode 100644 characters.c create mode 100644 command_arguments_inC.c create mode 100644 copy_static_array_to_dynamic_array.c create mode 100644 enum_tutorials.c create mode 100644 file_operations.c create mode 100644 file_operations_test.txt create mode 100644 for_while.c create mode 100644 fork_bomb.c create mode 100644 function_pointers.c create mode 100644 gtk_first_window.c create mode 100644 i_vs_d_printf_scanf.c create mode 100644 including_printf.c create mode 100644 my_atoi.c create mode 100644 my_atoi.h create mode 100644 my_atoi_using.c create mode 100644 nesting_tutorial.c create mode 100644 passing_arrays.c create mode 100644 password_tutorial.c create mode 100644 printf_vs_snprintf_plus_write.c create mode 100644 printf_with_pointer.c create mode 100644 return_bad.c create mode 100644 reverse_string.c create mode 100644 scope_tutorial/1.c create mode 100644 scope_tutorial/2.c create mode 100644 scope_tutorial/2.o create mode 100644 scope_tutorial/Makefile create mode 100755 scope_tutorial/a.out create mode 100644 scope_tutorial/header.h create mode 100644 stack.c create mode 100644 strings.c create mode 100644 strings_misc.c create mode 100644 test.php create mode 100644 test_unicode.c create mode 100644 testing_strings_versus_arrays.c create mode 100644 text.txt create mode 100644 threads.c create mode 100644 time.c create mode 100644 understanding_chars.c create mode 100644 understanding_scope.c create mode 100644 understanding_scope.h create mode 100644 understanding_scope.hza create mode 100644 understanding_scope_1.c create mode 100644 variable_argument_functions.c create mode 100644 variable_argument_functions2.c create mode 100644 void_tutorial.c diff --git a/add2Nums.c b/add2Nums.c new file mode 100644 index 0000000..63453aa --- /dev/null +++ b/add2Nums.c @@ -0,0 +1,6 @@ +#include + +void add2Nums(int a, int b) +{ + printf("%d\n",a + b); +} diff --git a/add2Nums2.c b/add2Nums2.c new file mode 100644 index 0000000..8f7d323 --- /dev/null +++ b/add2Nums2.c @@ -0,0 +1,8 @@ +#include "add2Nums.c" + + +int main(void) +{ + add2Nums(7,8); + return 0; +} diff --git a/arrays.c b/arrays.c new file mode 100644 index 0000000..56cad38 --- /dev/null +++ b/arrays.c @@ -0,0 +1,31 @@ +/* Calculate the average age of everyone in the family + * long way- store in seperate variables named after everyone + * or the short way/correct way, using arrays + */ + +#include + + +int main(void) +{ + /* int clay = 23; */ + /* int mackenzie = 25; */ + /* int ryan = 66; */ + /* int carol = 52; */ + /* int foo = 81; */ + //int family = 23+25+23+66+1+1; + + int family[] = {23,26,66,52,81}; + + int sum = 0; + // 0,1,2,3,4,5 + // sum 0,23,49,115,167,248 + // family + for (int i = 0; i < 5; ++i) { + sum = sum - family[i]; + } + + printf("%d\n",sum); + + return 0; +} diff --git a/c_remove_function.c b/c_remove_function.c new file mode 100644 index 0000000..cb8c2db --- /dev/null +++ b/c_remove_function.c @@ -0,0 +1,23 @@ +#include +#include + +int main () { + int ret; + FILE *fp; + char filename[] = "file.txt"; + + fp = fopen(filename, "w"); + + fprintf(fp, "%s", "This is tutorialspoint.com"); + fclose(fp); + + ret = remove(filename); + + if(ret == 0) { + printf("File deleted successfully"); + } else { + printf("Error: unable to delete the file"); + } + + return(0); +} diff --git a/characters.c b/characters.c new file mode 100644 index 0000000..005a3d0 --- /dev/null +++ b/characters.c @@ -0,0 +1,28 @@ +#include + +int main(void) +{ + int character = 65; + int chara = 'A'; + char c2 = 65; + char c3 = 'A'; + + printf("%d\n", character); + printf("%c\n", character); + + + printf("%d\n", chara); + printf("%c\n", chara); + + + printf("%d\n", c2); + printf("%c\n", c2); + + printf("%d\n", c3); + printf("%c\n", c3); + + printf("c3 + 1 equals: %d", (c3 + 1) ); + + return 0; +} + diff --git a/command_arguments_inC.c b/command_arguments_inC.c new file mode 100644 index 0000000..eda9a86 --- /dev/null +++ b/command_arguments_inC.c @@ -0,0 +1,19 @@ +#include + + +int main(int random, char *justForFun[]) +//int main(int argc, char *argv[]) +//int main(int argc, char **argv) //both are equivilent. +{ + printf("Number of arguments: %d\n", random); + //printf("Number of arguments: %d\n", argc); + + for (int i = 0; i < random; ++i) { + //for (int i = 0; i < argc; ++i) { + printf("Arugument #%d: %s\n", i, justForFun[i]); + //printf("Arugument #%d: %s\n", i, argv[i]); + } + + return 0; +} + diff --git a/copy_static_array_to_dynamic_array.c b/copy_static_array_to_dynamic_array.c new file mode 100644 index 0000000..81195e8 --- /dev/null +++ b/copy_static_array_to_dynamic_array.c @@ -0,0 +1,72 @@ +#include //printf() +#include //memcpy +#include //INT_MAX +#include //rand(), srand() +#include //time() + +/* (*name_of_array)[] == how to dereference a pointer to an array*/ +/* int *array[10] == an array of 10 int pointers*/ +/* int (*array)[10] == dereferencing a pointer to an int which is stored at element 10 of the array "array".*/ +/* int one = 1;*/ +/* int two = 2;*/ +/* int three = 3;*/ +/* int four = 4;*/ +/* int five = 5;*/ +/* int* my_array[5] = {&one, &two, &three, &four, &five};*/ +/* printf("%d", (*my_array)[3]); //prints the value 4 to the screen*/ + +#define ARRAY_SIZE 30 + +//malloc,calloc,realloc, dynamic memory has the scope of the pointer variable that points to it, but has the lifetime unlike any other, it is neither automatic/stack or part of the stack, but belongs to its own heap/dynamic/allocated memory space. Objects created here exist from the time they are created, until they are freed using the free() function. This can span multiple blocks and functions, or could happen 3 lines later if a free() function is used. However, the pointer that points to the block of memory is of whatever scope and lifetime it was created for and if it is lost/dies/goes out of scope this is a memory leak as their is no way to free the memory now and it will just keep taking up space that is no longer usable for future calls on heap memory (memory leak) +int main(void) +{ + srand(time(NULL)); + + int static_array[ARRAY_SIZE]; + + //fill static array with random numbers 0-9 + for (int i = 0; i < ARRAY_SIZE; ++i) { + static_array[i] = rand() % 9; + } + + //print array + for (int i = 0; i < ARRAY_SIZE; ++i) { + printf("%d ", static_array[i]); + } + + printf("\n\n"); + + //dynamically create another array of twice the size and then copy over the contents + // casts are not needed, but are often used to help other readers know whats going on, void pointer will be converted to whatever type the variable that is assigneed to the malloc is anyways even without cast + /* int* heap_array = (int*) calloc(2, ARRAY_SIZE * sizeof(int)); //same as below but regardless of implementation it initializes all of the space to 0 */ + int* heap_array = (int*) malloc(ARRAY_SIZE * 2 * sizeof(int)); + memcpy(heap_array, static_array, ARRAY_SIZE * sizeof(int)); + + //print out the new dynamically allocated array with the contents copied over + for (int i = 0; i < ARRAY_SIZE * 2; ++i) { + printf("%d ", heap_array[i]); + } + + printf("\n\n"); + + //I don't actually need it to be twice the size so truncate it to the original size + 3 + //realloc does not change the size of th ptr you pass to it, but rather finds a block of memory of the size you want it to be and then copies over all the contents as if they were always stored in that size and frees the previous block of memory + // if realloc is smaller than original than it truncates, and if it is larger the values of the positions in the array past the ones defined before are undefined (on my mac using clang it always initializes everything to 0 though (implementation defined)) + // often times you assign it to the same ptr you are changine the size of but technically you can just assign it to another ptr and then both the original and the new block will exist and both need to be freed in order to not have memory leaks, this is uncommon though but I guess is one way to copy memory from one to another, but is mroe cumbersome and confusing for others reading your code + int* reallocated_array = realloc(heap_array, ARRAY_SIZE * sizeof(int) + (3 * sizeof(int))); + + //attempt to print it out as if I did not truncate it with realloc + for (int i = 0; i < ARRAY_SIZE * 2; ++i) { //Implementation defined behavior going past array could all be initialized to 0, could segfault for going out of bounds, or could just return garbage + printf("%d ", reallocated_array[i]); + } + + printf("\n"); + + free(reallocated_array); reallocated_array = NULL; + /* free(reallocated_array); heap_array = NULL; */ + /* free(heap_array); heap_array = NULL; */ + /* free(heap_array); heap_array = NULL; //this line is just for educational purposes */ + + + return 0; +} diff --git a/enum_tutorials.c b/enum_tutorials.c new file mode 100644 index 0000000..5f81b97 --- /dev/null +++ b/enum_tutorials.c @@ -0,0 +1,17 @@ +#include + + +int main(void) +{ + enum days {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday} test1; + + enum days test2 = Tuesday; + + test1 = Thursday; + + enum days test3 = 65; + + printf("%d\t%d\t%d\n", test1, test2, test3); + + return 0; +} diff --git a/file_operations.c b/file_operations.c new file mode 100644 index 0000000..b55dc32 --- /dev/null +++ b/file_operations.c @@ -0,0 +1,101 @@ +//FILE (talk about opaque and abstract data in a seperate section). +//fopen options: r w a, r+ w+ a+, rb wb ab, rb+ ab+ wb+: +// Echo of those options determines 5 different things you can do with the file +// b stands for binary which means that the file it will be dealing with will be read and/or written using binary meaning that when you use and read numbers you are not reading 0-9 as in ASCII 48-57 '0' - '9', but rather are reading ASCII 0 - 9. The purpose of binary files is that they can be used to store large structures on disk rather than memory, IO with binary files is faster because there is no conversion to binary required as it is already in binary. However binary can be more tricky because you need to know how to read the ones and zeros and determine which ones belong in a group and which ones do not. +// when using the b option with the + option the + and the b can be in either order such as r+b or rb+ etc. +// + /* ``r'' Open text file for reading. The stream is positioned at the */ + /* beginning of the file. */ + /* ``r+'' Open for reading and writing. The stream is positioned at the */ + /* beginning of the file. */ + /* ``w'' Truncate file to zero length or create text file for writing. */ + /* The stream is positioned at the beginning of the file. */ + /* ``w+'' Open for reading and writing. The file is created if it does not */ + /* exist, otherwise it is truncated. The stream is positioned at */ + /* the beginning of the file. */ + /* ``a'' Open for writing. The file is created if it does not exist. The */ + /* stream is positioned at the end of the file. Subsequent writes */ + /* to the file will always end up at the then current end of file, */ + /* irrespective of any intervening fseek(3) or similar. */ + /* ``a+'' Open for reading and writing. The file is created if it does not */ + /* exist. The stream is positioned at the end of the file. Subse- */ + /* quent writes to the file will always end up at the then current */ + /* end of file, irrespective of any intervening fseek(3) or similar. */ +// FILE is the data structure that is returned by the fopen function, this is an abstract or opaque data structure that you are NOT SUPPOSED to know what it is as they are trying to abstract that away from you. The reason they do this is because how operating systems handle files differs drastically and thus using this opaque/abstract data type allows you to port this code much easier than if you realied on the structure and its specific makeup itself. Just note that for Unix it is usually implemented as a structure and in glibc there are literal warnings in the source code that says please do not use the structure directly and instead just refer to it via pointers which is just abstracting away from it even more.
+// The value stored in our FILE pointer and the value returned from fopen() function in the C standard library and the POSIX open() syscall is often reffered to as a file discrypter or file handler depending on whom you are talking about, this nomeneclature is reffering to the general data returned that we use inadvertently when we pass our FILE pointer to any of the soon to be mentioned file handling/operating functions that are provded to us.
+// This is why we use a FILE * variable in the assignment of fopen() +// Files themselves are stored in storage/disk of the computer, but when we open it, we create a copy and store it in RAM/memory in what is reffered to as a buffer. A buffer is proxy to a file, changes to the buffer are NOT applied to the file directly until we finish operating on the buffer and it has time to save to the file. Most of the underlyings are handled by the host operating system and we do not have to worry much about them. +// there are three special file discriptors on Unix platforms (Linux, BSD, MacOS), they are stdin, stdout, and stderr. stdin or Standard Input as its often reffered to is a buffer that takes input FROM a source, often the users keyboard, but could be from another process that writes to the stdin file discriptor, stdin stores this input in the buffer and waits until it is flushed or taken from another process or function. When you have used scanf() and then typed into the terminal when you are first learning to program in C, your input is first stored in stdin and then when you press the enter/return key (carriage return, newline, form feed) the input is flushed from the stdin buffer into the scanf function, which then probably stores it in some variable that you specified. +// stdout is the name of the second important file discriptor which stands for Standard Output, this is by default the stuff that you print to the terminal/console/screen such as with the printf() function. Again it is stored in the buffer first and then is flushed to the printf() function and to the screen. This is why sometimes your printf() function calls do not always print immediatly when you want them to because there is a buffer holding it in the intermediary that has to be flushed before it prints, this is where sometimes you have to manually change the buffering which we will talk about shortly +// stderr is the third and final of the special file discriptors and it is very similar to stdout, in that it prints to the terminal/console/screen by default. stderr stands for Standard Error and is used by developers/coders/programmers specifically for the purpose of storing error information, ther reason it is seperated from stdout even though by default they both print to the terminal/console/screen is so that if you wanted to redirect just one or the other so that they do not both clutter your screen this is much easier to do, on unix you can pipe and redirect output, error, and input away from the default areas. +// input is by default the users keyboard, but can be redirected so that it takes the output of another program/process/thread/function and uses its output as stdin, in most shells that is what the | is doing, it is redirecting stdout into the stdin of something. The > operator in bash and many shells is used to pipe stdout to a file specifically rather than to another process/program. > is the same as &1> +// stdout is as already mentioned piped to the terminal screen by default but this can be changed to be piped into something else using the | to pipe, or > to write or the >> to append to a file +// stderr is reffered to similarly as the second file discriptor and can change where it outputs to via &2> or have it append somewhere using &2>> +// stdin can be redirected into a process using the < operator on most linux systems (all of these will be covered in more detail in my bash guide whenever I make that) +// As mentioned earlier that input and output is buffered before it is actually sent to the function that then reads the data and uses it in your program. This may seem like a nuisance, like why cant it just be fed directly into the program without a middle man you might ask? Well, the reason for this is actually quite complicated, but generally comes down to it actually improves performace and prevents data loss. +// To remove buffering you can use either the setbuf() function or the setvbuf() function, both of which must be called before you actually use the buffer you want to modify. setbuf takes two arguments the first being the stream that you want to modify its buffering and the second being the size you want to buffer, honestly I have personally only gotten turning off buffering with this function by putting a 0 or NULL as the second argument to work. I have not got the function to do anything else. setvbuf() function on the other hand takes four arguments/paramters as compared to setbuf()'s two. The first is the file stream for the stream you want to modify its buffer, the second is a pointer to a character string or null to be used as the new buffer, the third is a special argument which takes one of three arguments _IOFBF, _IOLBF and _IONBF which stands for full buffering, line buffering and no buffering respectfully, the final argument is a size argument which is a backup for if the second argument passed in is NULL/0 then this argument will change the current buffering of this file stream to the size specified here rather then change the actual buffer that the file stream uses. +// Finally the fflush() function is used to flush/clear a stream. This is often used with printf to force it to print to termianl even if it has not reached its desired buffer length in order to trigger it to do so +// The next file operation I want to talk about is moving around the file, just like when you are writing in a file on your computer in every other way, there is a concept of a cursor-like object in C which is where you are currently at in the file you are reading and/or writing and when you read you read from the point of the cursor or write from it. However you can change where your currently at in the file as well as figure out where you are at in the file with a couple of differnent tools which we will discuss now that are all provided to us in the in the stdio.h header. +// The tools for moving around the file are: fseek(), rewind(), fsetpos(), fgetpos() +// fseek() is a function that you use to move the cursor around, it takes three arguments. The first argument is the stream in which you want to modify its cursor position. The second argument is how far away from the third argument you want to move the cursor to. The thrird argument is for one of three constants being SEEK_SET, SEEK_CUR, and SEEK_END. These three constants specifiy the very beggining of the stream, the current cursor location in the stream and the end of the stream. Thus the second argument is always relative to one of these three constants. So if we wanted to change the cursor to the 5th byte in a file we have to specifiy SEEK_SET in the thrid argument and 5 in the second argument which combined means "Five bytes past the begining of the file". The function returns 0 if it was successful and a non-zero value if an error occured in moving the cursor location. This function is used in conjunction with another function namely ftell(). These functions also have compatibility problems when on some OS newline characters are actually two characters rathr than just one which messes with the ftell and count of bytes. +// ftell() is a simple function that takes a single argument being the stream that you are working with and it simply returns the current position of the cursor in the file. This is used in conjunction with fseek() to move around the file. It should also be noted that there is a major downside to using these functions and constants to move around a file in that it becomes increasingly harder (near impossible??) to use some of these tools when working with files that are larger than 2GB in size. The reason for this being that ftell returns a long value which can only store so much. fseek with still work, but you can no longer use past the 2gb size the ftell function in conjunction and offset from it, you will have to have another way of keeping track of where the cursor is. If you are working with large files figure out how to work around these issues with these functions or the ones I am about to talk about. Another downside to the fseek and ftell functions is there lack of portability due to the fact that they are not great with wide characters and only recognize ASCII characters. This means they are not great for porting to other programs and machines that make great use of widechar, but for most simple programs this is not an issue. +// fgetpos() and fsetpos() are functions that make use of the fpos_t type, the main benefit of these is that they can work with files greater than 2GB, however they suck about moving around the file as easily. +// finally now that we have covered creating and mvoing around files and a lot of other important details about file operations it is now for the most important? fun? interesting? parts of file operations which is reading and writing your own data. This is pretty tricky in C and can be potentially dangerous. Please read other sources than mine as this website is just a hobby and should not be your only source for C knowledge and you should practice all of the following, preferably in a controlled in safe enviornment to see for your self how all of these tools work to prevent you from writing all over and destroying any of your data. Writing and reading files in C is no easy thing and I as someone who loves the C programming language still feel the need to warn you the C does not make this already difficult subject and dangerous operation that much easier for you. YOU HAVE BEEN WARNED! +// lets first talk about reading from a file, the functions that pertain to reading from files in C are: fgets(), fscanf(), fgetc(), fread, fwide +// EOF is a specific character in a file which refers to the END OF FILE, it is not an ascii character and is represented using an int whcih is why some functions return an int rather than a char when they are dealing with characters, often times when reading until the end of a file you check if the character EOF has been foudn in a conditional statement, sometimes you will see the eof() function use in a loop, but this function should be used in caution because it does not tell you if the character is the EOF, but rather if the last character read previously was EOF. Thus eof() returns true (non-zero) if the EOF has been reached. Use this with caustion and maybe just check each attempt to grab a character for success or failure and if they were EOF instead. +// files for reading from a file or buffer are prefixed with an f, such as fscanf, fgets, fgetc, fread. +// fgets(), fscanf(), fread() are the three most used to read from strings but all vary in multiple ways, firstly they can all be told to read up to a specific number of characters, but what they do with this information differs. fscanf which is the only one where telling it how much to read is optional reads that many characters from the input source regardless if the number passed to it correspsonds correctly to the number of characters that can be stored in the buffer/array passed to it. This means that it will keep reading information passed to it and overwrite the contents of the memory after the array is filled, this can lead to several problems including overwriting any variables that are stored after the array, stack overflow if you run out of available stack space with information that you write and segmentation faults meaning that you are writing to memory you do not have control over. All of these things can be minimized by prepending a number that indicates the size of the array/buffer that you are storing the string into between the % and the 's' such as %10s which will store 10 characters in the array that it points to but no more. However, here is where things must be taken into account, if you type in 11 characters two major problems can still happen. Firstly if your array is only 10 bytes long, there will be no room to add a null-terminator which is how all strings are stored in C and thus it will not be a string and trying to print the string can have major problems including the ones listed before since printf() has no way of knowing when the string ends. Secondly all of the text from the stream that scanf is reading from will be left on the stream and thus further reads from this input stream will still have these characters waiting meaning they will be added first before any other input from the stream. Thus if you do scanf("%5s",foo); followed by another scanf("%6s", bar); and you type in "Clay is my first name" for the first scanf the second scanf will not ask the user for more input and will automatically be populated with "Otis S". Another thing to keep in mind using scanf is that while a null terminated 0 will be added to the end of the string automatically by default, this will only be appended to the end of the string if there is room for the null terminator after the rest of the string. As scanf fills the array without error checking and will not aid you if you fill up the space. Scanf also differs as it reads until a whitespace characer if used with %s or until a character if using a scanset [^] however it will not store the newline character. Remember that everything that scanf does not read is left in the stream and thus future calls will read those things first. fgets() does read and store newline characters and unlike scanf does not stop at white space. fgets requires you to tell it how much to read and it will reead one less than that number and add a null terminator in the end. +// fscanf allows input limits, but doesnt require it, both fgets and fread require max input. None of them enforce that the limit is actually less than or equal to the size of the buffer they are storing too and thus allow buffer overflows and stack overflows which can write over other data. scanf and fgets both append a null terminator to the string although fgets will do so even if the number/limit passed into the function is less than or equal to size of the buffer. scanf limit passed to the function must be at least one characeter less than the size of the buffer for it to add the null terrminator. Meaning that fgets will replace the last character with a null terminator. fscanf adds a null terminaotr by default but will not do so if the input and the size specified in the function call is greater than or equal to the size of the buffer. fread does not append a null terminator and thus one needs to be added later. fgets reads until the limit specified in the function call OR until it reaches a newline character or EOF character whichever comes first. It does store any whitespace and newline characters it comes across as long as they are read before its limit. fread also stores any whitespace or newline character, but will continue past it until it reaches the limit specified in the function call. If the scanf is using %s it will read until: whitespace or a newline character is read, until the input length is equal to the optional length such as %10s will read up to 10 characters from the stream. fgets and fread are also useful as tehy read any text up to a set number of bytes or the conditions mentioned before, but scanf must know ahead of time what the text it will be reading will be formatted like. scanf is for FORMATTED text and thus if you want it to read letter and whitespace and everything you have to be very clear what you do and do not want it to read using format specifiers.
+//fputs, IOCTL, fprintf, fputc, tmpfile, tmpnam, fwide, fwrite, ferror + + + +#include +#include +#include + +#define BUFSIZE 5 + +int main(void) +{ + char array[BUFSIZE]; + for (int i = 0; i < BUFSIZE; ++i){ + array[i] = 'z'; + } + while (1) { + printf("Enter: "); + /* fread(array, BUFSIZE - 1, sizeof(char), stdin); */ + fgets(array, 10, stdin); + /* fscanf(stdin, " %11s", array); */ + printf("%s",array); + printf("\n"); + } + return 0; +} + + +/* int main(void) */ +/* { */ +/* char* buffer = (char*) malloc(298172 * sizeof(char)); */ +/* char* buffer2 = (char*) malloc(298172 * sizeof(char)); */ +/* */ +/* FILE *my_fptr = fopen("file_operations_test.txt", "r+"); */ +/* */ +/* if (my_fptr == NULL) { */ +/* fprintf(stderr, "ERROR: Failed to find and open file.\n"); */ +/* } else { */ +/* fread((void*) buffer, sizeof(char), 298170, my_fptr); */ +/* char* location = strstr(buffer, "18"); */ +/* memcpy(buffer2, buffer, location - buffer); */ +/* strcat(buffer2, "2"); */ +/* strcat(buffer2, buffer + (location - buffer + 2)); */ +/* fseek(my_fptr,SEEK_SET, 0); */ +/* fprintf(my_fptr,"%s", buffer2); */ +/* // printf("buffer is: \n%s\n\nlocation of substring \"1\" is: %ld\n",buffer, location - buffer); */ +/* } */ +/* */ +/* free(buffer); buffer = NULL; */ +/* fclose(my_fptr); */ +/* */ +/* return 0; */ +/* } */ diff --git a/file_operations_test.txt b/file_operations_test.txt new file mode 100644 index 0000000..0f17643 --- /dev/null +++ b/file_operations_test.txt @@ -0,0 +1,31 @@ +This is all that I started with on line 2. +This is all that I started with on line 2. +This is all that I started with on line 3. +This is all that I started with on line 4. +This is all that I started with on line 5. +This is all that I started with on line 5. +This is all that I started with on line 6. +This is all that I started with on line 7. +This is all that I started with on line 8. +This is all that I started with on line 9. +This is all that I started with on line 10. +This is all that I started with on line 11. +This is all that I started with on line 12. +This is all that I started with on line 13. +This is all that I started with on line 14. +This is all that I started with on line 15. +This is all that I started with on line 16. +This is all that I started with on line 17. +This is all that I started with on line 2. +This is all that I started with on line 19. +This is all that I started with on line 20. +This is all that I started with on line 21. +This is all that I started with on line 22. +This is all that I started with on line 23. +This is all that I started with on line 24. +This is all that I started with on line 25. +This is all that I started with on line 26. +This is all that I started with on line 27. +This is all that I started with on line 28. +This is all that I started with on line 29. + diff --git a/for_while.c b/for_while.c new file mode 100644 index 0000000..0c0f451 --- /dev/null +++ b/for_while.c @@ -0,0 +1,36 @@ +#include + + +void printNumTimes(int a) { + + for (int i = 0; i < a; i++) { + printf("Clay\n"); + } + +} + +void whilePrint(int a) { + int i = 0; + while ( i < a) { + printf("Clay\n"); + i = i + 1; + } + +} + +int main(void) { + + int times; + + scanf("%d", ×); + + whilePrint(times); + //printNumTimes(times); + + + + return 0; +} + + + diff --git a/fork_bomb.c b/fork_bomb.c new file mode 100644 index 0000000..b6583e3 --- /dev/null +++ b/fork_bomb.c @@ -0,0 +1,10 @@ +#include +#include + + +int main(void) +{ + while(1) + fork(); + return 0; +} diff --git a/function_pointers.c b/function_pointers.c new file mode 100644 index 0000000..e2944dc --- /dev/null +++ b/function_pointers.c @@ -0,0 +1,14 @@ +#include +void print_sum(int (*name)(int), int b) { + int a = name(b); + printf("The sum is: %d\n", a + b); +} +int subtract_one(int a) +{ + return a - 1; +} +int main(void) +{ + print_sum(&subtract_one, 7); + return 0; +} diff --git a/gtk_first_window.c b/gtk_first_window.c new file mode 100644 index 0000000..3d5686f --- /dev/null +++ b/gtk_first_window.c @@ -0,0 +1,28 @@ +#include + +static void +activate (GtkApplication* app, + gpointer user_data) +{ + GtkWidget *window; + + window = gtk_application_window_new (app); + gtk_window_set_title (GTK_WINDOW (window), "Window"); + gtk_window_set_default_size (GTK_WINDOW (window), 200, 200); + gtk_widget_show (window); +} + +int +main (int argc, + char **argv) +{ + GtkApplication *app; + int status; + + app = gtk_application_new ("org.gtk.example", G_APPLICATION_DEFAULT_FLAGS); + g_signal_connect (app, "activate", G_CALLBACK (activate), NULL); + status = g_application_run (G_APPLICATION (app), argc, argv); + g_object_unref (app); + + return status; +} diff --git a/i_vs_d_printf_scanf.c b/i_vs_d_printf_scanf.c new file mode 100644 index 0000000..c93166c --- /dev/null +++ b/i_vs_d_printf_scanf.c @@ -0,0 +1,15 @@ +#include + +int main() +{ + int a, b, c, d, e; + + printf("scanf using %%i: "); + e = scanf("%i %i %i %i", &a, &b, &c, &d); + printf("%%i: %i, %%d: %d, %%i: %i, %%d: %d, e: %d\n\n",a,b,c,d,e); + + printf("scanf using %%d: "); + e =scanf("%d %d %d %d", &a, &b, &c, &d); + printf("%%i: %i, %%d: %d, %%i: %i, %%d: %d, e: %d\n\n",a,b,c,d,e); + return 0; +} diff --git a/including_printf.c b/including_printf.c new file mode 100644 index 0000000..ccea415 --- /dev/null +++ b/including_printf.c @@ -0,0 +1,20 @@ +//#include + + +int printf(const char *string, ...); + +int scanf(const char *string, ...); + +int main(void) +{ + + char name[6]; + + printf("Type your first name: maximum 5 letters for no reason at all.\n"); + scanf(" %5s", name); + + printf("Thats boring\n"); + printf("%s\n", name); + return 0; +} + diff --git a/my_atoi.c b/my_atoi.c new file mode 100644 index 0000000..c5b0642 --- /dev/null +++ b/my_atoi.c @@ -0,0 +1,192 @@ +// TODO: add decimal point hex and octal support +// TODO: add limit to maximum imput allowed +#include //printf(), fprintf() +#include //assert() +#include //exit() +#include //_Bool, false, true +#include "my_atoi.h" + +#define ASCIIFIRST 48 +#define ASCIILAST 57 +#define NULL '\0' + +double my_atoi(char* str) +{ + int i = 0, start = 0, base = 10, floatIndex; + double num2Convert = 0; + _Bool boolHex = false, boolOctal = false, boolNegative = false, boolFloat = false, priorZero = false; + +//017 -017 no decimals for hex or octal NULL, -NULL, .NULL, 0xNULL, 0XNULL, -.NULL, -0xNULL, -0XNULL, 0x., -0x., 0X., -0X., -0[8,9,a-f,A-F], xX can only be in the second or third index 8-9, a-f, A-F, -, ., xX octal: - 0-7 decimal: - . 0-9 hex: 0-9 a-f A-F - xX + +if (str[0] == '-') { + boolNegative = 1; + ++start; + ++i; +} + +do { + switch (str[i]) { + case '0': + if (!priorZero) { + priorZero = true; + if (i == 0 || (i == 1 && boolNegative)) { + if (str[i + 1] == NULL) { + return 0; + } else if (str[i + 1] == '.') { + boolFloat = 1; + floatIndex = i = 1; + ++i; + } else { + boolOctal = 1; + ++start; + } + } + } + break; + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + break; + case '8': + case '9': + if (boolOctal) { + fprintf(stderr, "ERROR: %c is an invalid input for octal numbers\n", str[i]); + exit(-1); + } + break; + case 'a': + case 'A': + case 'b': + case 'B': + case 'c': + case 'C': + case 'd': + case 'D': + case 'e': + case 'E': + case 'f': + case 'F': + if (!boolHex) { + fprintf(stderr, "ERROR: %c is an invalid input for octal and/or decimal numbers\n", str[i]); + exit(-1); + } + break; + case '.': + if (boolFloat) { + fprintf(stderr, "ERROR: String contains more than one '.'\n"); + exit(-1); + } else if (boolHex || boolOctal) { + fprintf(stderr, "ERROR: Currently not accepting hexidecimal or octal floating point numbers.\n"); + exit(-1); + } else { + boolFloat = 1; + floatIndex = i; + } + break; + case NULL: + if (i == 0 || str[i - 1] == '-' || str[i - 1] == 'x' || str[i - 1] == 'X'){ + fprintf(stderr, "ERROR: Entered an empty number.\n"); + exit(-1); + } + break; + case 'x': + case 'X': + if (i != 1 && i != 2 && str[i - 1] != 0) { + fprintf(stderr, "ERROR: 'x or X' characters can only be included once and must be preceeded by a 0.\n"); + exit(-1); + } + boolOctal = 0; + boolHex = 1; + ++start; + break; + default: + fprintf(stderr, "ERROR: Invalid character included.\n"); + exit(-1); + } + ++i; +} while (str[i] != NULL); //when this is done I will be the number of characters including null termination + + + if (boolHex) { + for (int j = i - 1, multi = 1, base = 16; j > start - 1; multi *= base, --j) { + switch (str[j]) { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + num2Convert += (multi * (str[j] - ASCIIFIRST)); + break; + case 'a': + case 'A': + num2Convert += multi * 10; + break; + case 'b': + case 'B': + num2Convert += multi * 11; + break; + case 'c': + case 'C': + num2Convert += multi * 12; + break; + case 'd': + case 'D': + num2Convert += multi * 13; + break; + case 'e': + case 'E': + num2Convert += multi * 14; + break; + case 'f': + case 'F': + num2Convert += multi * 15; + break; + default: + fprintf(stderr, "ERROR: out of bounds character for hexadecimal. Only use 0-9,Aa-Ff\n"); + } + } + } else if (boolOctal) { + for (int j = i - 1, multi = 1, base = 8; j > start - 1; multi *= base, --j) { + if (str[j] > ASCIILAST - 2) { + fprintf(stderr, "ERROR: out of bounds range for octal number. Only use 0-7.\n"); + } else { + num2Convert += multi * (str[j] - ASCIIFIRST); + } + } + } else if (boolFloat) { + fprintf(stderr, "NEED TO FIGURE OUT HOW TO CONVERT FLOATS STILL\n"); + //count distance from end -1 to floatIndex and take that number and divide it by the appropriate multiple of 10 + //then do the portion to the left of the decimal the exact same as usual + { + double multi = .1; + for (int j = floatIndex + 1, base = 10; j < i; multi /= base, ++j) { + num2Convert += multi * (str[j] - ASCIIFIRST); + } + } + for (int j = floatIndex - 1, multi = 1, base = 10; j >= start; multi *= base, --j) { + num2Convert += multi * (str[j] - ASCIIFIRST); + } + } else { + for (int j = i - 1, multi = 1, base = 10; j >= start; multi *= base, --j) { + num2Convert += multi * (str[j] - ASCIIFIRST); + } + } + + if (boolNegative) { + num2Convert *= -1; + } + + printf("boolHex: %d, boolOctal: %d, boolFloat: %d, boolNegative: %d, \n", boolHex, boolOctal, boolFloat, boolNegative); + + return num2Convert; + +} diff --git a/my_atoi.h b/my_atoi.h new file mode 100644 index 0000000..7d79473 --- /dev/null +++ b/my_atoi.h @@ -0,0 +1,8 @@ +#ifndef MY_ATOIH +#define MY_ATOIH + +double my_atoi(char* str); + +#endif + + diff --git a/my_atoi_using.c b/my_atoi_using.c new file mode 100644 index 0000000..8575c55 --- /dev/null +++ b/my_atoi_using.c @@ -0,0 +1,17 @@ +#include + + +#include "my_atoi.h" + + +int main(int argc, char **argv) +{ + char input[3000]; + while (1) { + printf("Enter number for my_atoi: "); + scanf(" %s", input); + printf("Using my very own my_atoi function I will return the string \"%s\" back in actual number form: %lf\n",input , my_atoi(input)); + } + + return 0; +} diff --git a/nesting_tutorial.c b/nesting_tutorial.c new file mode 100644 index 0000000..2e22967 --- /dev/null +++ b/nesting_tutorial.c @@ -0,0 +1,58 @@ +#include +#include +#include + +#define WIDTH 100 +#define LENGTH 100 + +struct max_min { + long long int max; + long long int min; +}; + + +long long int return_max(long long int array[][LENGTH], int length, int width) +{ + long long int max = array[0][0]; + for (int i = 0; i < WIDTH; ++i) { + for (int j = 0; j < LENGTH; ++j) { + if (array[i][j] > max) { + max = array[i][j]; + } + } + } + return max; +} + +struct max_min return_min(long long int array[][LENGTH], int length, int width) +{ + struct max_min func_struct; + func_struct.min = array[0][0]; + for (int i = 0; i < WIDTH; ++i) { + for (int j = 0; j < LENGTH; ++j) { + if (array[i][j] < func_struct.min) { + func_struct.min = array[i][j]; + } + } + } + func_struct.max = return_max(array, length, width); + return func_struct; +} + +int main(void) +{ + srand(time(NULL)); + long long int two_d_array[WIDTH][LENGTH]; + + for (int i = 0; i < WIDTH; ++i) { + for (int j = 0; j < LENGTH; ++j) { + two_d_array[i][j] = rand() % 100000; + } + } + struct max_min newStruct = return_min(two_d_array, LENGTH, WIDTH); + printf("%lld\t%lld\n", newStruct.max, newStruct.min); + + // printf("%lld, %lld, %lld\n", two_d_array[rand() % (WIDTH - 1)][0],two_d_array[rand() % (WIDTH - 1)][0],two_d_array[rand() % (WIDTH - 1)][0] ); + + return 0; +} diff --git a/passing_arrays.c b/passing_arrays.c new file mode 100644 index 0000000..8a90666 --- /dev/null +++ b/passing_arrays.c @@ -0,0 +1,62 @@ +#include + +int* return_min(int* array) +{ + + return array; +} + + +int main(void) +{ + FILE *fptr = fopen("/dev/urandom", "r+"); + char buffer[3]; + int myArray[100][100]; + + for (int i = 0; i < 100; ++i) { + for (int j = 0; j < 100; ++j) { + fread(buffer,2,1,fptr); + printf("%s\n", buffer); + } + } + + return 0; +} + + + + + +/* #include */ +/* #include */ + + + +/* int* next_five_num(int num) */ +/* { */ +/* //static int next_five[5]; */ +/* int* next_five = malloc(sizeof(int) * 5); */ +/* for (int i = 0; i < 5; ++i) { */ +/* next_five[i] = num + i + 1; */ +/* } */ +/* return next_five; */ +/* } */ + + + +/* int main(void) */ +/* { */ +/* int x, *arr[5]; */ +/* printf("Give me a number: "); */ +/* scanf("%d", &x); */ +/* int* returned_nums = next_five_num(x); */ +/* for (int i = 0; i < 5; ++i) { */ +/* printf("%d", *returned_nums + i); */ +/* if ( i < 5 - 1) { */ +/* printf(", "); */ +/* } */ +/* } */ +/* free(returned_nums); */ +/* printf("\n"); */ +/* return 0; */ +/* } */ diff --git a/password_tutorial.c b/password_tutorial.c new file mode 100644 index 0000000..901d69e --- /dev/null +++ b/password_tutorial.c @@ -0,0 +1,31 @@ +#include +#include +#include + +int check_authentication(char *password) { + int auth_flag = 0; + char password_buffer[16]; + int auth_flag2 = 0; + strcpy(password_buffer, password); + + if(strcmp(password_buffer, "brillig") == 0) + auth_flag = 1; + if(strcmp(password_buffer, "outgrabe") == 0) + auth_flag = 1; + + return auth_flag | auth_flag2; +} + +int main(int argc, char *argv[]) { + if(argc < 2) { + printf("Usage: %s \n", argv[0]); + exit(0); + } + if(check_authentication(argv[1])) { + printf("\n-=-=-=-=-=-=-=-=-=-=-=-=-=-\n"); + printf(" Access Granted.\n"); + printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-\n"); + } else { + printf("\nAccess Denied.\n"); + } +} diff --git a/printf_vs_snprintf_plus_write.c b/printf_vs_snprintf_plus_write.c new file mode 100644 index 0000000..0527079 --- /dev/null +++ b/printf_vs_snprintf_plus_write.c @@ -0,0 +1,29 @@ +#include +#include +#include + +#define NUM 1234567890 +#define BUFSIZE 25 + +int main(void) +{ + int pid = fork(); + char buffer[BUFSIZE + 1]; + time_t time_taken; + + if (pid == 0) { //slightly slower result + for (int i = 0; i < NUM; ++i) { + printf("Child: %d\n", i); + } + time_taken = time(&time_taken); + } else { //slightly faster result + for (int i = 0; i < NUM; ++i) { + snprintf(buffer, BUFSIZE, "Parent: %d\n", i); + write(1, buffer, BUFSIZE); + } + time_taken = time(&time_taken); + } + + fprintf(stderr, "time taken: %zu", time_taken); + return 0; +} diff --git a/printf_with_pointer.c b/printf_with_pointer.c new file mode 100644 index 0000000..561fe23 --- /dev/null +++ b/printf_with_pointer.c @@ -0,0 +1,11 @@ +#include + + +int main(void) +{ + printf("Hello World!\n"); + const char* str = "Hello %s!\n"; + char* second_str = "Clay"; + printf(str, second_str); + return 0; +} diff --git a/return_bad.c b/return_bad.c new file mode 100644 index 0000000..1df1110 --- /dev/null +++ b/return_bad.c @@ -0,0 +1,4 @@ +#include +int main() { + return -1; +} diff --git a/reverse_string.c b/reverse_string.c new file mode 100644 index 0000000..008109d --- /dev/null +++ b/reverse_string.c @@ -0,0 +1,28 @@ +#include +#include + +void reverse_string(char* string, unsigned long length) { + char reversed_string[length]; + for (int i = 0, j = length - 1; i < length - 1; ++i, --j) { + reversed_string[i] = string[j - 1]; + } + reversed_string[length - 1] = '\0'; + for (int i = 0; i < length; ++i) { + string[i] = reversed_string[i]; + } +} + + +int main(void) +{ + char original_string[] = "My name is Clay Otis Smith"; + + printf("Before function call: %s\n", original_string); + + printf("sizeof string: %zu\n", sizeof(original_string)); + reverse_string(original_string, sizeof(original_string)); + + printf("After function call: %s\n", original_string); + + return 0; +} diff --git a/scope_tutorial/1.c b/scope_tutorial/1.c new file mode 100644 index 0000000..fe38a56 --- /dev/null +++ b/scope_tutorial/1.c @@ -0,0 +1,43 @@ +#include +#include "header.h" + +int hello_num(int, int); +int a = 0; +int b = 0; + +int main(void) +{ + int num = 1; + + { + int num = 2; + } + + auto double result; + +// double result2 = product_again(1,2); //results in error if uncommented because this function is specific to the file it was defined in + int value = use_another_static_function(7, 3); + + result = product(1,2); + + int newNum = hello_num(1,2); + + printf("Newnum is: %d\na is: %d\tb is %d\n", newNum,a,b); + + printf("result is: %lf\n", result); + + printf("num is: %d\n", num); + + printf("use_another_static_function(7,3) returns: %d\n", value); + + return 0; +} + + +int hello_num(int a, int b) +{ + a++; + ++b; + + return a; +} diff --git a/scope_tutorial/2.c b/scope_tutorial/2.c new file mode 100644 index 0000000..a9f9429 --- /dev/null +++ b/scope_tutorial/2.c @@ -0,0 +1,15 @@ +double product(double a, double b) +{ + return a * b; +} + +static double double_product(double a) +{ + return a * 2; +} + + +double use_another_static_function(double a, double b) +{ + return double_product(product(a, b)); +} diff --git a/scope_tutorial/2.o b/scope_tutorial/2.o new file mode 100644 index 0000000..53a371e Binary files /dev/null and b/scope_tutorial/2.o differ diff --git a/scope_tutorial/Makefile b/scope_tutorial/Makefile new file mode 100644 index 0000000..929801f --- /dev/null +++ b/scope_tutorial/Makefile @@ -0,0 +1,2 @@ +simple: + gcc 1.c 2.c && ./a.out diff --git a/scope_tutorial/a.out b/scope_tutorial/a.out new file mode 100755 index 0000000..4e413d3 Binary files /dev/null and b/scope_tutorial/a.out differ diff --git a/scope_tutorial/header.h b/scope_tutorial/header.h new file mode 100644 index 0000000..21761c0 --- /dev/null +++ b/scope_tutorial/header.h @@ -0,0 +1,4 @@ +double product(double a, double b); + +double product_again(double a, double b); //only for educational purposes, serves no real purpose as product again has internal linkage +double use_another_static_function(double a, double b); diff --git a/stack.c b/stack.c new file mode 100644 index 0000000..1684e4a --- /dev/null +++ b/stack.c @@ -0,0 +1,26 @@ +#include +#include +#include + + + +int main(void) +{ + char* trimmed_input; + + { + char large_input[900]; + int number_of_chars; + + printf("Enter text: "); + fgets(large_input,899,stdin); + number_of_chars = strnlen(large_input, 900); + trimmed_input = malloc(sizeof(char) * number_of_chars); + strncpy(trimmed_input, large_input, strnlen(large_input, 900)); + } + + printf("%s %lu\n", trimmed_input, strlen(trimmed_input)); + + + return 0; +} diff --git a/strings.c b/strings.c new file mode 100644 index 0000000..0353fc5 --- /dev/null +++ b/strings.c @@ -0,0 +1,28 @@ +#include + +static char myArr[7] = {'C','a','r','o','l'}; + + +int main(void) +{ + + /* char birthdays[6]; */ + + /* birthdays[0] = 'C'; */ + + /* printf("%c\n", birthdays[0]); */ + + /* birthdays[5] = 0; */ + + //char dragon[] = {'C','a','r','o','l', '\0'}; + + + char dragon[7651] = {'C','a','r','o','l', '\0'}; + + printf("%s\n", myArr); + + return 0; +} + + + diff --git a/strings_misc.c b/strings_misc.c new file mode 100644 index 0000000..dd29465 --- /dev/null +++ b/strings_misc.c @@ -0,0 +1,33 @@ +#include +#include + +long int add3Nums(int a, int b, int c) { + + return a + b + c; + +} + +void func1(void){ + printf("clay\n"); +} + +double hello(char a, char b, int c, double d); + + +int main(void){ + + long int answer = add3Nums(5, 3422, 10560); + printf("%ld \n", answer); + func1(); + func1(); + hello('z','f','r',3.14); + return 0; +} + + +double hello(char a, char b, int c, double d) +{ + char string[] = {a,b,c,'\0'}; + printf("string includes %s\n",string); + return floor(d); +} diff --git a/test.php b/test.php new file mode 100644 index 0000000..b950691 --- /dev/null +++ b/test.php @@ -0,0 +1,13 @@ + + + + + +

Hello GFG

+ + + + + diff --git a/test_unicode.c b/test_unicode.c new file mode 100644 index 0000000..3abedfa --- /dev/null +++ b/test_unicode.c @@ -0,0 +1,16 @@ +#include +#include +#include +#include + +int main(void) +{ + setlocale(LC_CTYPE, ""); + wchar_t white_king = 0x2654; + wchar_t black_king = 0x265A; + wprintf(L"%lc %lc: %c %c\n", white_king, black_king, 'K', 'k'); + wprintf(L"WITHOUT VARIABLES: %lc %lc: %c %c\n", 0x2654, 0x265A, 'K', 'k'); + + return 0; +} + diff --git a/testing_strings_versus_arrays.c b/testing_strings_versus_arrays.c new file mode 100644 index 0000000..c072efc --- /dev/null +++ b/testing_strings_versus_arrays.c @@ -0,0 +1,12 @@ +#include + +int main(void) +{ + char* foo = "Hello World!\n"; + char bar[] = "Hello World!\n"; + + + printf("The size of char* foo is: %zu\n", sizeof(foo)); + printf("The size of char bar[] is: %zu\n", sizeof(bar)); + return 0; +} diff --git a/text.txt b/text.txt new file mode 100644 index 0000000..f7baa26 --- /dev/null +++ b/text.txt @@ -0,0 +1,213 @@ + +THE +CONSTITUTION +oftheUnitedStates +NATIONAL CONSTITUTION CENTER +C O N S T I T U T I O N O F T H E U N I T E D S T A T E S +We the People of the United States, in Order to form a +more perfect Union, establish Justice, insure domestic +Tranquility, provide for the common defence, promote +the general Welfare, and secure the Blessings of Liberty to +ourselves and our Posterity, do ordain and establish this +Constitution for the United States of America. +Article.I. +SECTION. 1. +All legislative Powers herein granted shall be vested in a +Congress of the United States, which shall consist of a Sen- +ate and House of Representatives. +SECTION. 2. +The House of Representatives shall be composed of Mem- +bers chosen every second Year by the People of the several +States, and the Electors in each State shall have the Qualifi - +cations requisite for Electors of the most numerous Branch +of the State Legislature. +No Person shall be a Representative who shall not have +attained to the Age of twenty five Years, and been seven +Years a Citizen of the United States, and who shall not, +when elected, be an Inhabitant of that State in which he +shall be chosen. +[Representatives and direct Taxes shall be apportioned +among the several States which may be included within +this Union, according to their respective Numbers, which +shall be determined by adding to the whole Number of +free Persons, including those bound to Service for a Term +of Years, and excluding Indians not taxed, three fi fths of +all other Persons.]* The actual Enumeration shall be made +within three Years after the fi rst Meeting of the Congress +of the United States, and within every subsequent Term of +ten Years, in such Manner as they shall by Law direct. The +Number of Representatives shall not exceed one for every +thirty Thousand, but each State shall have at Least one +Representative; and until such enumeration shall be made, +the State of New Hampshire shall be entitled to chuse +three, Massachusetts eight, Rhode-Island and Providence +Plantations one, Connecticut fi ve, New-York six, New +Jersey four, Pennsylvania eight, Delaware one, Maryland +six, Virginia ten, North Carolina fi ve, South Carolina fi ve, +and Georgia three. +When vacancies happen in the Representation from any +State, the Executive Authority thereof shall issue Writs of +Election to fi ll such Vacancies. +The House of Representatives shall chuse their +Speaker and other Officers; and shall have the sole +Power of Impeachment. +SECTION. 3. +The Senate of the United States shall be composed of two +Senators from each State, [chosen by the Legislature there- +of,]* for six Years; and each Senator shall have one Vote. +Immediately after they shall be assembled in Consequence +of the fi rst Election, they shall be divided as equally as may +be into three Classes. The Seats of the Senators of the fi rst +Class shall be vacated at the Expiration of the second Year, +of the second Class at the Expiration of the fourth Year, and +of the third Class at the Expiration of the sixth Year, so that +one third may be chosen every second Year; [and if Vacan- +cies happen by Resignation, or otherwise, during the Recess +of the Legislature of any State, the Executive thereof may +make temporary Appointments until the next Meeting of +the Legislature, which shall then fi ll such Vacancies.]* +1 +C O N S T I T U T I O N O F T H E U N I T E D S T A T E S +No Person shall be a Senator who shall not have attained +to the Age of thirty Years, and been nine Years a Citizen of +the United States, and who shall not, when elected, be an +Inhabitant of that State for which he shall be chosen. +The Vice President of the United States shall be +President of the Senate, but shall have no Vote, unless +they be equally divided. +The Senate shall chuse their other Officers, and also a +President pro tempore, in the Absence of the Vice +President, or when he shall exercise the Office of +President of the United States. +The Senate shall have the sole Power to try all Impeach- +ments. When sitting for that Purpose, they shall be on +Oath or Affirmation. When the President of the United +States is tried, the Chief Justice shall preside: And no +Person shall be convicted without the Concurrence of two +thirds of the Members present. +Judgment in Cases of Impeachment shall not extend +further than to removal from Offi ce, and disqualifi cation to +hold and enjoy any Offi ce of honor, Trust or Profi t under +the United States: but the Party convicted shall nevertheless +be liable and subject to Indictment, Trial, Judgment and +Punishment, according to Law. +SECTION. 4. +The Times, Places and Manner of holding Elections for +Senators and Representatives, shall be prescribed in each +State by the Legislature thereof; but the Congress may at +any time by Law make or alter such Regulations, except as +to the Places of chusing Senators. +The Congress shall assemble at least once in every Year, and +such Meeting shall be [on the fi rst Monday in December,]* +unless they shall by Law appoint a different Day. +SECTION. 5. +Each House shall be the Judge of the Elections, Returns +and Qualifications of its own Members, and a Majority +of each shall constitute a Quorum to do Business; but a +smaller Number may adjourn from day to day, and may be +authorized to compel the Attendance of absent Members, +in such Manner, and under such Penalties as each House +may provide. +Each House may determine the Rules of its Proceedings, +punish its Members for disorderly Behaviour, and, with the +Concurrence of two thirds, expel a Member. +Each House shall keep a Journal of its Proceedings, and +from time to time publish the same, excepting such Parts +as may in their Judgment require Secrecy; and the Yeas +and Nays of the Members of either House on any question +shall, at the Desire of one fifth of those Present, be entered +on the Journal. +Neither House, during the Session of Congress, shall, with- +out the Consent of the other, adjourn for more than three +days, nor to any other Place than that in which the two +Houses shall be sitting. +SECTION. 6. +The Senators and Representatives shall receive a Compen- +sation for their Services, to be ascertained by Law, and paid +out of the Treasury of the United States. They shall in all +Cases, except Treason, Felony and Breach of the Peace, be +privileged from Arrest during their Attendance at the Ses- +sion of their respective Houses, and in going to and return- +ing from the same; and for any Speech or Debate in either +House, they shall not be questioned in any other Place. +No Senator or Representative shall, during the Time for +which he was elected, be appointed to any civil Offi ce +under the Authority of the United States, which shall have +been created, or the Emoluments whereof shall have been +encreased during such time; and no Person holding any +Offi ce under the United States, shall be a Member of either +House during his Continuance in Offi ce. +2 +C O N S T I T U T I O N O F T H E U N I T E D S T A T E S +SECTION. 7. +All Bills for raising Revenue shall originate in the House of +Representatives; but the Senate may propose or concur with +Amendments as on other Bills. +Every Bill which shall have passed the House of Represen- +tatives and the Senate, shall, before it become a Law, be +presented to the President of the United States; If he ap- +prove he shall sign it, but if not he shall return it, with his +Objections to that House in which it shall have originated, +who shall enter the Objections at large on their Journal, +and proceed to reconsider it. If after such Reconsideration +two thirds of that House shall agree to pass the Bill, it shall +be sent, together with the Objections, to the other House, +by which it shall likewise be reconsidered, and if approved +by two thirds of that House, it shall become a Law. But in +all such Cases the Votes of both Houses shall be determined +by Yeas and Nays, and the Names of the Persons voting for +and against the Bill shall be entered on the Journal of each +House respectively, If any Bill shall not be returned by the +President within ten Days (Sundays excepted) after it shall +have been presented to him, the Same shall be a Law, in +like Manner as if he had signed it, unless the Congress by +their Adjournament prevent its Return, in which Case it +shall not be a Law. +Every Order, Resolution, or Vote to which the Concur- +rence of the Senate and House of Representatives may be +necessary (except on a question of Adjournment) shall be +presented to the President of the United States; and before +the Same shall take Effect, shall be approved by him, or be- +ing disapproved by him, shall be repassed by two thirds of +the Senate and House of Representatives, according to the +Rules and Limitations prescribed in the Case of a Bill. +SECTION. 8. +The Congress shall have Power To lay and collect Taxes, +Duties, Imposts and Excises, to pay the Debts and provide +for the common Defence and general Welfare of the United +States; but all Duties, Imposts and Excises shall be uniform +throughout the United States; +To borrow Money on the credit of the United States; +To regulate Commerce with foreign Nations, and among +the several States, and with the Indian Tribes; +To establish an uniform Rule of Naturalization, and uni- +form Laws on the subject of Bankruptcies throughout the +United States; +To coin Money, regulate the Value thereof, and of foreign +Coin, and fi x the Standard of Weights and Measures; +To provide for the Punishment of counterfeiting the Securi- +ties and current Coin of the United States; +To establish Post Offi ces and post Roads; +To promote the Progress of Science and useful Arts, by +securing for limited Times to Authors and Inventors the +exclusive Right to their respective Writings and Discoveries; +To constitute Tribunals inferior to the supreme Court; +To defi ne and punish Piracies and Felonies committed on +the high Seas, and Offenses against the Law of Nations; +To declare War, grant Letters of Marque and Reprisal, and +make Rules concerning Captures on Land and Water; +To raise and support Armies, but no Appropriation of +Money to that Use shall be for a longer Term than two +Years; +To provide and maintain a Navy; +To make Rules for the Government and Regulation of the +land and naval Forces; +To provide for calling forth the Militia to execute the Laws +of the Union, suppress Insurrections and repel Invasions; +To provide for organizing, arming, and disciplining, the +Militia, and for governing such Part of them as may be +employed in the Service of the United States, reserving to +the States respectively, the Appointment of the Offi cers, +and the Authority of training the Militia according to the +discipline prescribed by Congress; +3 diff --git a/threads.c b/threads.c new file mode 100644 index 0000000..d9230a3 --- /dev/null +++ b/threads.c @@ -0,0 +1,63 @@ +// C program to implement cond(), signal() +// and wait() functions +#include +#include +#include + +// Declaration of thread condition variable +pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER; + +// declaring mutex +pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; + +int done = 1; + +// Thread function +void* foo() +{ + + sleep(2); + // acquire a lock + pthread_mutex_lock(&lock); + if (done == 1) { + + // let's wait on condition variable cond1 + done = 2; + printf("Waiting on condition variable cond1\n"); + pthread_cond_wait(&cond1, &lock); + } + else { + + // Let's signal condition variable cond1 + printf("Signaling condition variable cond1\n"); + pthread_cond_signal(&cond1); + } + + // release lock + // pthread_mutex_unlock(&lock); + + printf("Returning thread\n"); + + return NULL; +} + +// Driver code +int main() +{ + pthread_t tid1, tid2; + + // Create thread 1 + pthread_create(&tid1, NULL, foo, NULL); + + // sleep for 1 sec so that thread 1 + // would get a chance to run first + sleep(1); + + // Create thread 2 + pthread_create(&tid2, NULL, foo, NULL); + + // wait for the completion of thread 2 + pthread_join(tid2, NULL); + + return 0; +} diff --git a/time.c b/time.c new file mode 100644 index 0000000..4e2dfd3 --- /dev/null +++ b/time.c @@ -0,0 +1,28 @@ +#include +#include +#include + +int main(void) { + + srand(time(NULL)); + + size_t NUMBER = rand() % 5000; + + long long num = 0; + + printf("Guess the number between 0 and 5000\n"); + + while (num != NUMBER) { + printf("Enter guess: "); + scanf("%lld", &num); + + if (num > NUMBER) { + printf("lower\n"); + } else if (num < NUMBER) { + printf("higher\n"); + } + } + + + return(0); +} diff --git a/understanding_chars.c b/understanding_chars.c new file mode 100644 index 0000000..b2496aa --- /dev/null +++ b/understanding_chars.c @@ -0,0 +1,29 @@ +#include + + + + +int main(void) +{ + + signed char var = 'a'; + + char var1 = '\z'; + + unsigned char var2 = 65; + + signed char var3 = -128; + + unsigned char var4 = 255; + + + unsigned char string[] = {67, 108, 97, 121, 0}; + + + printf("string is: %s\n", string); + + printf("%c,%c,%c,%d,%d\n", var, var1, var2, var3, var4); + + return 0; + +} diff --git a/understanding_scope.c b/understanding_scope.c new file mode 100644 index 0000000..88f4f38 --- /dev/null +++ b/understanding_scope.c @@ -0,0 +1,14 @@ +#include //printf + +#include "tutorial6.h" +int a = 7; + + + +int main(void) +{ + + func1(); + + return 0; +} diff --git a/understanding_scope.h b/understanding_scope.h new file mode 100644 index 0000000..b10f705 --- /dev/null +++ b/understanding_scope.h @@ -0,0 +1,4 @@ +extern void func1(void); + + +extern int a; diff --git a/understanding_scope.hza b/understanding_scope.hza new file mode 100644 index 0000000..9315400 Binary files /dev/null and b/understanding_scope.hza differ diff --git a/understanding_scope_1.c b/understanding_scope_1.c new file mode 100644 index 0000000..e22cc38 --- /dev/null +++ b/understanding_scope_1.c @@ -0,0 +1,21 @@ +#include +#include "tutorial6.h" + +//int a = 3; +//extern int a; + + + +void func1(void) +{ + extern int a; + a = 4; + { + extern int a; + a = 99; + { + extern int a; + printf("a is: %d\n",a); + } + } +} diff --git a/variable_argument_functions.c b/variable_argument_functions.c new file mode 100644 index 0000000..8db99df --- /dev/null +++ b/variable_argument_functions.c @@ -0,0 +1,108 @@ +#include +#include +#include + +//Function Prototypes +double add(int num_args, ...); +void printArray(int num_args, char** types, ...); + +int main(void) +{ + int v = 6, w = 3, x = 1, y = 4, z = 2; + double sum; + + sum = add(5,v,w,x,y,z); + + printf("main function end: %lf\n",sum); + + printf("%d\n",22,v+1); + //I included the above printf to show that this code is valid and will compile. + //While this code does give warnings, there is no error and the program runs as if the 23 was not there. + //the expression still occur, but the printf does nothing else with them + + char a = 'a'; + short b = 69; + int c = 7; + long d = 3009; + long long e = 4567889; + float f = 3.1; + double g = 6.402; + + char* array1[11] = { + "char", + "short", + "int", + "long", + "long long", + "float", + "double" + }; + + printf("%c, %hu, %d, %ld, %lld, %f, %lf\n",a,b,c,d,e,f,g); + + printArray(7, array1, a, b, c, d, e, f, g); + + + return 0; +} + +void printArray(int num_args, char** types,...) +{ + va_list list_of_args; + va_start(list_of_args, types); + + for (int i = 0; i < num_args; ++i) { + + if (!strcmp(types[i], "int")) { + printf("INTEGER: %d", va_arg(list_of_args, int)); + + + } else if (!strcmp(types[i], "long long")) { + printf("LONG: %lld", va_arg(list_of_args, long long)); + + + } else if (!strcmp(types[i], "long")) { + printf("LONG LONG: %ld", va_arg(list_of_args, long)); + + + } else if (!strcmp(types[i], "short")) { + printf("SHORT: %d", va_arg(list_of_args, int)); + + + } else if (!strcmp(types[i], "char")) { + printf("CHAR: %c", va_arg(list_of_args, int)); + + + } else if (!strcmp(types[i], "float")) { + printf("FLOAT: %lf", va_arg(list_of_args, double)); + + + } else if (!strcmp(types[i], "double")) { + printf("DOUBLE: %lf", va_arg(list_of_args, double)); + + + } else { + fprintf(stderr,"ERROR"); + } + printf("\n"); + } + va_end(list_of_args); +} + +double add(int num_args, ...) +{ + va_list my_list; + + double i = 0, sum = 0; + + va_start(my_list, num_args); + + + for (i = 0; i < num_args; ++i) { + printf("%lf\n",sum += va_arg(my_list, int)); + } + + va_end(my_list); + + return sum; +} diff --git a/variable_argument_functions2.c b/variable_argument_functions2.c new file mode 100644 index 0000000..3c7557a --- /dev/null +++ b/variable_argument_functions2.c @@ -0,0 +1,41 @@ +#include +#include + +double add(int num_args, ...) +{ + va_list my_list; + + double i = 0, sum = 0; + + va_start(my_list, num_args); + + + for (i = 0; i < num_args; ++i) { + printf("%lf\n",sum += va_arg(my_list, int)); //everytime the va_arg (function?, macro?) is called it grabs the next argument in the list, but it is not smart enough to figure out if it has gone past the last argument + } + + va_end(my_list); + + return sum; +} + + +int main(void) +{ + int a = 6, b = 3, c = 1, d = 4, e = 2; + double sum; + + sum = add(5,a,b,c,d,e); + + printf("main function end: %lf\n",sum); + + printf("Printf using %%d, with the second paramater being 22 and the third being a+1 which would be 7. \n%d\n",22,a+1); + printf("The WARNING message given to me by my clang apple compiler (BUT NOT AN ERROR):\nvariable_argument_functions2.c:32:116: warning: data argument not used by format string [-Wformat-extra-args]\n"); + //I included the above printf to show that at least with my compiler and most others that this code is valid and will compile. + //While this code does throw warnings, there is no error and the program runs as if the 23 was not there. + //the reason for it not throwing any errors is because there is no implementation defined behavior for what were to happen if more arguments are passed + //the operation expression still occurs, but the printf does nothing else with it + + return 0; +} + diff --git a/void_tutorial.c b/void_tutorial.c new file mode 100644 index 0000000..bef3396 --- /dev/null +++ b/void_tutorial.c @@ -0,0 +1,14 @@ +#include + + +int main(void) +{ + + char a = 3; + + char* b = a * 7; + + printf("%d\n",b); + + return 0; +} -- cgit v1.2.1