Skip to content

Instantly share code, notes, and snippets.

@BobVul
Last active September 21, 2020 19:07
Show Gist options
  • Save BobVul/5071142 to your computer and use it in GitHub Desktop.
Save BobVul/5071142 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;
}
@BobVul
Copy link
Author

BobVul commented Jun 27, 2019

@rcorsari 5 years late, but ... yea, the faster way would be to use SIMD instructions to process multiple bytes at a time, using SIMD (SSE, AVX, etc.) intrinsics. But they're fairly complex to use. And a good compiler might generate them for a simple loop like this anyway.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment