Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cycle that works on all files that fit in memory
#include <stdio.h>
#include <stdlib.h>
#define INCREMENT 1024
char *buf;
void read(FILE *in) {
int len;
char *bufind = buf;
long buflen = INCREMENT;
while ((len = fread(bufind, 1, INCREMENT, in)) > 0) {
if (len != INCREMENT) {
break;
}
buflen += INCREMENT;
bufind = realloc(buf, buflen);
if (!bufind) {
fprintf(stderr, "Failed to realloc!\n");
exit(4);
}
buf = bufind;
bufind = buf + buflen - INCREMENT;
}
bufind[len] = '\0';
}
void write(char *v) {
for (int count = atoi(v); count > 0; count--) {
printf("%s", buf);
}
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Need a file (/dev/stdin for stdin) and a count!\n");
exit(1);
}
FILE *in = fopen(argv[1], "r");
if (!in) {
fprintf(stderr, "Need a valid file to open!\n");
exit(2);
}
buf = malloc(INCREMENT);
if (!buf) {
fprintf(stderr, "Could not perform initial malloc!\n");
exit(3);
}
read(in);
fclose(in);
write(argv[2]);
free(buf);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.