Skip to content

Instantly share code, notes, and snippets.

@skinp
Created January 16, 2012 01:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skinp/1618414 to your computer and use it in GitHub Desktop.
Save skinp/1618414 to your computer and use it in GitHub Desktop.
Reads a file and prints content to stdout. Uses a dynamic buffer. Is not meant to be used...
/*
* readfile
*
* Patrick Pelletier (pp.pelletier@gmail.com) - July 2010
*
* Program that reads a file and outputs it's content to stdout.
*
* Uses a dynamic buffer to store the content temporarly.
* It makes a good example of how to allocate a dynamic char buffer.
* Was written as an exercice while bored with no internet connection @Recon 2010
*
* TODO: Maybe make some methods
* Extract the dynamic buffer code to make a generic module
*/
#include <stdio.h>
#include <stdlib.h>
#define INCREMENT 10
// Basic dynamic buffer structure
struct string {
char *buffer;
unsigned int maxLength;
unsigned int size;
};
int main(int argc, char **argv) {
// Argument check + usage
char *programName = argv[0];
if (argc != 2) {
printf("Usage: %s <filename>\n", programName);
exit(1);
}
// Open the file to read
char *fileName = argv[1];
FILE *file = fopen(fileName, "r");
if (file == NULL) {
printf("Unable to open file: %s\n", fileName);
exit(2);
}
// Allocate initial space for buffer
struct string s;
s.buffer = malloc(INCREMENT*sizeof(char));
if (s.buffer == NULL) {
printf("Problem allocating memory");
exit(3);
}
s.maxLength = 10;
s.size = 0;
// Reads file 1 char at a time and puts it in buffer, allocating space if needed
char c;
while ((c = fgetc(file)) != EOF) {
if (s.size == s.maxLength) {
s.buffer = realloc(s.buffer, sizeof(char)*(INCREMENT+s.size));
if (s.buffer == NULL) {
printf("Problem allocating memory");
exit(4);
}
s.maxLength += INCREMENT;
}
s.buffer[s.size] = c;
s.size++;
}
// Add missing \0
if (s.size == s.maxLength) {
s.buffer = realloc(s.buffer, sizeof(char *)*(1+s.size));
if (s.buffer == NULL) {
printf("Problem allocating memory");
exit(4);
}
s.maxLength += INCREMENT;
}
s.buffer[s.size] = '\0';
s.size++;
/* Debugging messages
printf("Size %d\n", s.size);
printf("Max %d\n", s.maxLength);
unsigned int j;
for (j = 0; j <= s.maxLength; j++) {
printf("Pos %d Char %x \n", j, s.buffer[j]);
}
*/
// Print string, close everything
printf("%s", s.buffer);
free(s.buffer);
fclose(file);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment