Skip to content

Instantly share code, notes, and snippets.

@BobVul
Last active October 10, 2023 15:48
Show Gist options
  • Save BobVul/5070989 to your computer and use it in GitHub Desktop.
Save BobVul/5070989 to your computer and use it in GitHub Desktop.
Check for nonzero data in a stream. Answers http://superuser.com/q/559772/117590.
#include <cstdio>
#define BUFFER_SIZE 1024
int main() {
FILE* file = stdin;
char buffer[BUFFER_SIZE];
long long bytes_read = 0;
long long progress = 0;
long long nonzero = 0;
while (bytes_read = fread(buffer, 1, BUFFER_SIZE, file)) {
for (long long i = 0; i < bytes_read; i++) {
progress++;
if (buffer[i] != 0) {
nonzero++;
printf("%lld: %x\n", progress, buffer[i]);
}
}
fprintf(stderr, "%lld bytes processed\r", progress);
}
fprintf(stderr, "\n");
int error = 0;
if (error = ferror(file)) {
fprintf(stderr, "Error reading file, code: %d\n", error);
return -1;
}
printf("%lld nonzero characters encountered.\n", nonzero);
return nonzero;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment