-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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