Advertisement
jjessie

lowercase.c

Jul 31st, 2011
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.87 KB | None | 0 0
  1. /*#####################
  2. # <lowercase.c>              
  3. #  07-29-11 John Jessie
  4. #  <program will read from file>
  5. #  <and print to screen one line>
  6. #  <at a time in lowercase>
  7. # */
  8.  
  9. #include <stdio.h> /* required for file ops */
  10. #include <stdint.h> /* required for UINT_MAX */
  11. #include <string.h> /* required for strncpy */
  12. #include <ctype.h> /* required for tolower */
  13. #include <limits.h> /* required for UINT_MAX */
  14. #include <stdlib.h>
  15.  
  16. char *ReadFile(char *filename);
  17.  
  18. char *ReadFile(char *filename)
  19. {
  20.     // declare file pointer f
  21.     FILE *f;
  22.    
  23.     f = fopen(filename, "r");
  24.     // growable buffer for chars
  25.     char *buffer = NULL;
  26.    
  27.     // capacity of buffer
  28.     unsigned int capacity = 0;
  29.    
  30.     // number of chars actually in buffer
  31.     unsigned int n = 0;
  32.    
  33.     // character read or EOF
  34.     int c;
  35.    
  36.     // iteratively get chars from stdin
  37.     while ( ( c = tolower(fgetc(f)) ) != EOF)
  38.     {
  39.         // grow buffer if necessary
  40.         if (n + 1 > capacity)
  41.         {
  42.             // determine new capacity: start @32 then 2x
  43.             if (capacity == 0)
  44.                 capacity = 32;
  45.             else if (capacity <= (UINT_MAX / 2))
  46.                 capacity *= 2;
  47.             else
  48.             {
  49.                 free(buffer);
  50.                 return NULL;
  51.             }
  52.            
  53.             // extend buffer's capacity
  54.             char *temp = realloc(buffer, capacity * sizeof(char));
  55.             if (temp == NULL)
  56.             {
  57.                 free(buffer);
  58.                 return NULL;
  59.             }
  60.             buffer = temp;
  61.         }
  62.        
  63.         // append current char to buffer
  64.         buffer[n++] = c;
  65.     }
  66.    
  67.     // return NULL if no chars received
  68.     if (n == 0 && c == EOF)
  69.       return NULL;
  70.        
  71.     // minimize buffer
  72.     char *minimal = malloc((n + 1) * sizeof(char));
  73.     strncpy(minimal, buffer, n);
  74.     free(buffer);
  75.    
  76.     // terminate string
  77.     minimal[n] = '\0';
  78.    
  79.     // return string
  80.     return minimal;
  81. }
  82.  
  83. int main(int argc, char *argv[])
  84. {
  85.     if ( argc < 2 )
  86.     {
  87.         printf("No file specified to read.");
  88.         return 1;
  89.     }
  90.     char *filename = argv[1];
  91.     printf("%s", ReadFile(filename) );
  92.     return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement