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; | |
} |
This comment has been minimized.
This comment has been minimized.
@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
This comment has been minimized.
Hello, one kind curiosity, I'm attempting to learn some basic ANSI C (not C++, though)
I see that you run a "for" cycle to check if the bytes are all 0.
The curiosity and question is this: once you have loaded the buffer, is there a way to make an instant XOR of all its bytes content?
If yes, that would avoid the run of the "for" cycle and so run even faster, isn't it?
Thank you for teaching.
Robert