Advertisement
Guest User

Read file contents similar to cat

a guest
Apr 18th, 2020
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.19 KB | None | 0 0
  1. /*
  2.     Compiled with: gcc -ansi -pedantic -o main main.c
  3.     Called with: ./main [filePath]
  4. */
  5.  
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8.  
  9. #define BUFFER_SIZE 256
  10.  
  11. /*
  12.     If a single startup param is granted, it'll use it as a filepath and print the contents of that file.
  13. */
  14. int main(int argumentCount, char* arguments[]) {
  15.     /* Pointer we'll need later */
  16.     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. */
  17.     FILE* file;
  18.  
  19.     /* arguments[0] is the startup-path */
  20.     /* If an additional startup parameter is entered, then that's expected to be the filepath  */
  21.     if(argumentCount == 2) {
  22.         filePath = arguments[1];  /* Doesn't copy the value of arguments[0], but makes filePath point to the same location as arguements[0] */
  23.     }
  24.     else {
  25.         /* malloc = memory allocate -> Here it allocates how much memory a single char uses times how many the buffer is set to contain */
  26.         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 */
  27.         printf("Enter filepath to read from: \n"); /* print-formated, though no placeholders are used in this */
  28.         scanf("%s", filePath); /* Read a string into filePath*/
  29.     }
  30.    
  31.     file = fopen(filePath, "r"); /* Opens filepath in read only and returns a pointer to the stream */
  32.  
  33.     if(file == NULL) { /* fopen returns a null-pointer if the file wasn't found */
  34.         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 */
  35.         return EXIT_FAILURE;
  36.     }
  37.     else {
  38.         char readBuffer[BUFFER_SIZE];
  39.         while(fgets(readBuffer, BUFFER_SIZE, file) != NULL) { /* Repeatedly read into buffer and print it, until fgets returns NULL when trying to read */
  40.             printf("%s",readBuffer);
  41.         }
  42.     }
  43.  
  44.     /* Free any memory that was allocated dynamically */
  45.     if(argumentCount != 2) free(filePath);
  46.  
  47.     return EXIT_SUCCESS;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement