Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Compiled with: gcc -ansi -pedantic -o main main.c
- Called with: ./main [filePath]
- */
- #include <stdio.h>
- #include <stdlib.h>
- #define BUFFER_SIZE 256
- /*
- If a single startup param is granted, it'll use it as a filepath and print the contents of that file.
- */
- int main(int argumentCount, char* arguments[]) {
- /* Pointer we'll need later */
- char* filePath; /* Fun fact: Strings are just arrays of characters, and arrays are just pointers to a location in memory, where the next N bytes are part of it. */
- FILE* file;
- /* arguments[0] is the startup-path */
- /* If an additional startup parameter is entered, then that's expected to be the filepath */
- if(argumentCount == 2) {
- filePath = arguments[1]; /* Doesn't copy the value of arguments[0], but makes filePath point to the same location as arguements[0] */
- }
- else {
- /* malloc = memory allocate -> Here it allocates how much memory a single char uses times how many the buffer is set to contain */
- filePath = malloc(sizeof(char) * BUFFER_SIZE); /* This doesn't change what was at the initial location of filepath, it moves the pointer, so filePath now points to where the new memory was allocated */
- printf("Enter filepath to read from: \n"); /* print-formated, though no placeholders are used in this */
- scanf("%s", filePath); /* Read a string into filePath*/
- }
- file = fopen(filePath, "r"); /* Opens filepath in read only and returns a pointer to the stream */
- if(file == NULL) { /* fopen returns a null-pointer if the file wasn't found */
- printf("File '%s' not found", filePath); /* Here %s is used to enter a string, but it could be any of these https://en.wikipedia.org/wiki/Printf_format_string#Type_field */
- return EXIT_FAILURE;
- }
- else {
- char readBuffer[BUFFER_SIZE];
- while(fgets(readBuffer, BUFFER_SIZE, file) != NULL) { /* Repeatedly read into buffer and print it, until fgets returns NULL when trying to read */
- printf("%s",readBuffer);
- }
- }
- /* Free any memory that was allocated dynamically */
- if(argumentCount != 2) free(filePath);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement