Skip to content

Instantly share code, notes, and snippets.

@hashimaziz1
Forked from BobVul/iszero-fast.cpp
Created September 21, 2020 19:07
Show Gist options
  • Save hashimaziz1/9166e349b5eecbb00ad232732f1a447c to your computer and use it in GitHub Desktop.
Save hashimaziz1/9166e349b5eecbb00ad232732f1a447c to your computer and use it in GitHub Desktop.
Check for nonzero data in a stream, quickly and without output. 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;
while (bytes_read = fread(buffer, 1, BUFFER_SIZE, file)) {
for (long long i = 0; i < bytes_read; i++) {
if (buffer[i] != 0) {
printf("Nonzero byte encountered.\n");
return 1;
}
}
}
int error = 0;
if (error = ferror(file)) {
fprintf(stderr, "Error reading file, code: %d\n", error);
return -1;
}
printf("All bytes are zero.\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment