Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*#####################
- # <lowercase.c>
- # 07-29-11 John Jessie
- # <program will read from file>
- # <and print to screen one line>
- # <at a time in lowercase>
- # */
- #include <stdio.h> /* required for file ops */
- #include <stdint.h> /* required for UINT_MAX */
- #include <string.h> /* required for strncpy */
- #include <ctype.h> /* required for tolower */
- #include <limits.h> /* required for UINT_MAX */
- #include <stdlib.h>
- char *ReadFile(char *filename);
- char *ReadFile(char *filename)
- {
- // declare file pointer f
- FILE *f;
- f = fopen(filename, "r");
- // growable buffer for chars
- char *buffer = NULL;
- // capacity of buffer
- unsigned int capacity = 0;
- // number of chars actually in buffer
- unsigned int n = 0;
- // character read or EOF
- int c;
- // iteratively get chars from stdin
- while ( ( c = tolower(fgetc(f)) ) != EOF)
- {
- // grow buffer if necessary
- if (n + 1 > capacity)
- {
- // determine new capacity: start @32 then 2x
- if (capacity == 0)
- capacity = 32;
- else if (capacity <= (UINT_MAX / 2))
- capacity *= 2;
- else
- {
- free(buffer);
- return NULL;
- }
- // extend buffer's capacity
- char *temp = realloc(buffer, capacity * sizeof(char));
- if (temp == NULL)
- {
- free(buffer);
- return NULL;
- }
- buffer = temp;
- }
- // append current char to buffer
- buffer[n++] = c;
- }
- // return NULL if no chars received
- if (n == 0 && c == EOF)
- return NULL;
- // minimize buffer
- char *minimal = malloc((n + 1) * sizeof(char));
- strncpy(minimal, buffer, n);
- free(buffer);
- // terminate string
- minimal[n] = '\0';
- // return string
- return minimal;
- }
- int main(int argc, char *argv[])
- {
- if ( argc < 2 )
- {
- printf("No file specified to read.");
- return 1;
- }
- char *filename = argv[1];
- printf("%s", ReadFile(filename) );
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement